1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Creating pow in java

  1. Jan 18, 2009 #1
    1. The problem statement, all variables and given/known data
    Define a recursive method named pow that takes two integers, x and n, and returns the result of raising x to the n-th power. Assume that n is non-negative.

    pow(5, 0) ==> 1
    pow(2, 10) ==> 1024
    pow(-3, 2) ==> 9



    2. Relevant equations



    3. The attempt at a solution
    I'm totally fresh to java, and am not used to or comfortable with recursion.
    public static int pow(int x, int n) {

    I don't know what to do. Should I have some increasing value to count up to when x has been multiplied by itself n times? I know scheme which seems to be a bit of a different ball game here. Any help would be appreciated.
    1. The problem statement, all variables and given/known data



    2. Relevant equations



    3. The attempt at a solution
     
  2. jcsd
  3. Jan 19, 2009 #2

    Dick

    User Avatar
    Science Advisor
    Homework Helper

    pow(n,k)=pow(n,k-1)*n, isn't it? pow(n,0)=1. Isn't that a pretty recipe for recursion? You don't have to count anything at all.
     
  4. Jan 19, 2009 #3
    yep, and remember to check the base case first:
    Code (Text):
    if(k==1) return n;
    or:
    Code (Text):
    if(k==0) return 1;
    if you will.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Creating pow in java
  1. String in java (Replies: 7)

  2. Java program (Replies: 3)

  3. Java prob. (Replies: 1)

  4. HeapSort Java (Replies: 3)

Loading...