开发者

How to get Nth Power of any number [closed]

开发者 https://www.devze.com 2023-03-18 11:58 出处:网络
Closed. This question is off-topic. It is not currently accepting answers. Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed. This question is off-topic. It is not currently accepting answers.

Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 11 years ago.

开发者_Go百科 Improve this question

I faced an interview. where I was asked the following question

Write a function in any of programming language that computes the nth power of a number w/o using + * or ^ or declaring a new variable inside the function or using any library function (eg Math lib in java).

I have used pow function of java Math.pow(a, b)

Thanks


They're asking whether you understand recursion. Considering x ^ k for some integer k,

  • when k < 0, xk = xk+1 / x
  • when k = 0, xk = 1
  • when k > 0, xk = xk-1 * x

Turning this into code shouldn't be too bad. Let's use multiplication for now, and take it out later.

double recursivePower(double x, int k) {
    if (k < 0) {
        return power(x, ++k) / x;
    } else if (k == 0) {
        return 1;
    } else {
        return power(x, --k) * x;
    }
}

Now, to get rid of the multiplication. Since n * m = n / (1/m), we can rewrite the last calculation as power(x, --k) / (1/x):

double recursivePower(double x, int k) {
    if (k < 0) {
        return recursivePower(x, ++k) / x;
    } else if (k == 0) {
        return 1;
    } else {
        return recursivePower(x, --k) / (1 / x);
    }
}

Fractional exponents could probably be done in the same style. If they want irrational exponents to be handled in the same way, I'd ask for Google and a fair amount of time to think about the problem.


static public int power(int value, int pow){
    if(pow == 0) return 1;

    return value * power(value, pow -1);
}


Done in JavaScript:

function power(num,pow){
  if (pow == 0) return 1
  num /= 1/(power(num,--pow))
  return num
}

Call it like:

power(2,0) // -> 1
power(5,2) // -> 25
power(7,3) // -> 343

I feel like inverse division is cheating the no * operator rule, but eh, maybe that's what they were looking for.


I am using java programming language. The interviewer restricted you to declare a new variable inside the method better you pass it to the function. The interviewer didnt restrict you to use division operator (/) so you can use that.

static double getNthPowerOfNumber(double originalNumber,
        int power) {


    if (power == 0) {
        return 1;
    }
    if (originalNumber == 0) {
        return 0;
    } else {
        originalNumber/=1/getNthPowerOfNumber(originalNumber, --power);

        return originalNumber;
    }



}

if you want to get 5th power of a number 3 then write System.out.println("4..double..." + getNthPowerOfNumber(4, 1));

0

精彩评论

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