Tuesday, June 14, 2016

PowerN - Recursion

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

Java :
1
2
3
4
5
public int powerN(int base, int n) {
  if(n == 0 ) return 1;
  if(n == 1) return base;
  return base*powerN(base,n-1);
}

Output :


Oooowh...btw... We can use DinamycProgramming style here.... It will gonna look like this :
1
2
3
4
5
6
7
8
9
public int powerN(int base, int n) {
 int[] hasil = new int[n];
 hasil[0] = base;
 for(int i=1; i<n; i++)
 {
   hasil[i] = base*hasil[i-1];
 }
 return hasil[n-1];
}

The output will be same, but DinamycProgramming style is faster than recursive at a big n... :D

No comments:

Post a Comment