Java: Base to Power of 'N' Problem in Java [closed]
Problem Statement:
Given base and n that are both 1 or more, compute the value of base to the n power, so powerN(3, 2)
is 9 (3 squared).
Example
powerN(3, 1) → 3
powerN(3, 2) → 9
powerN(3, 3) → 27
The function signature is public int powerN(int base, int n)
I'm finding it to difficult to solve this? Help me out.
EDIT: I need a solution which does not uses built in mathematical formulas and recursionpublic int powerN(int base, int n) {
int result = 1;
for (int i = 0; i < n; i++) {
result *= base;
}
return result;
}
The most popular method of doing this is like this:
sum = base
while (power > 1)
if (power is even)
sum = sum * sum
power = power / 2
else
sum = sum * base
power = power - 1
return sum
You can convert to Java, I just wanted to give you the general idea.
You can use recursion:
public int powerN(int base, int n)
{
if (n == 0) {
return 1;
} else {
return (powerN(base, n-1) * base);
}
}
assuming your power stays under int limit
int out = 1;
for(int i=n; i>0; i--)
out = out*base;
return out;
Fast way the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int from Elias Yarrkov
Exponentiation by squaring.
public static long powerN(long base, long n)
{
long result = 1;
while (n > 0)
{
if ((n & 1) == 1)
result *= base;
n >>= 1;
base *= base;
}
return result;
}
public int powerN(int base, int n) {
return Double.intValue(Math.pow ( base, n));
}
Ok I saw you can't use built in functions:
public int powerN(int base, int n) {
if (n == 0) {
return 1;
} else {
int result = 1;
for (int i = 0; i < n; i++) {
result = result * base;
}
return result;
}
}
精彩评论