开发者

Java: Base to Power of 'N' Problem in Java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answ开发者_开发技巧ered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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 recursion


public 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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜