FastPrepPower with Integer Exponents

Power with Integer Exponents

NVIDIA logoNVIDIA● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given a real number x and integer n, implement myPow(x, n) to return x^n without a built-in power function.

For this exercise, a zero exponent returns 1 and a negative exponent returns the reciprocal of the positive power. When x = 0, n is positive.

Function

myPow(x: double, n: int) → double

Examples

Example 1

x = 3.0n = 4return = 81.0

Four factors of three give 81.

Example 2

x = 4.0n = -2return = 0.0625

The reciprocal of sixteen is 0.0625.

Example 3

x = 2.5n = 0return = 1.0

Any nonzero base to exponent zero is one.

Constraints

  • -100 < x < 100; x is finite.
  • -2^31 <= n <= 2^31 - 1.
  • The mathematical result is between -10^4 and 10^4 and representable as a finite double; very small magnitudes may underflow to zero.
  • Outputs are compared using absolute or relative tolerance 10^-9.

More NVIDIA problems

See NVIDIA hiring insights
public double myPow(double x, int n) {
    // Write your code here.
}
x3.0
n4
expected81.0
Checking account…