Java > Recursion-1 > powerN (CodingBat Solution)

Problem:

Given base and n that are both 1 or more, compute recursively (no loops) the value of base to the n power, so powerN(3, 2) is 9 (3 squared).

powerN(3, 1) → 3
powerN(3, 2) → 9
powerN(3, 3) → 27


Solution:

public int powerN(int base, int n) {
  if (n == 0) return 1;
  return base * powerN(base, n-1);
}


2 comments :

  1. Why isn't proper?
    return powerN(base, n);
    It's illogical to me.

    ReplyDelete
  2. public int powerN(int base, int n) {
    if (n == 1) return base;
    return base*powerN(base,n-1);
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact