Creating pow in Java: Learn Recursive Solution

  • Context: Comp Sci 
  • Thread starter Thread starter cgrumiea
  • Start date Start date
  • Tags Tags
    Java
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 2K views
cgrumiea
Messages
4
Reaction score
0

Homework Statement


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



Homework Equations





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.
 
Physics news on Phys.org
yep, and remember to check the base case first:
Code:
if(k==1) return n;
or:
Code:
if(k==0) return 1;
if you will.