FastPrepPositive Nth Root with Gradient Descent

Positive Nth Root with Gradient Descent

Akuna Capital logoAkuna Capital● HardINTERNNEW GRADFULLTIMEPHONE SCREENONSITE INTERVIEW

Problem statement

Given a positive real number a and a positive integer n, return the unique positive real root r satisfying r^n = a.

Use gradient descent on the convex objective F(x) = x^(n+1) / (a(n+1)) - x for x > 0. Its gradient is g(x) = x^n/a - 1. Choose a positive initialization, a stable step size and a stopping rule.

Your answer must satisfy |answer - r| <= 0.000001 * max(1, |r|), where r is the exact positive root. Large and small inputs must stay finite. Computing integer powers at an iterate is allowed. Do not obtain the answer through Newton updates, a root formula, or bisection to the required answer tolerance. A bracket may be used only to initialize gradient descent to a fixed relative width, such as hi/lo <= 1 + 1/n; the subsequent accuracy refinement must use gradient updates.

For n = 1, the root is simply a. Return that boundary directly.

Function

positiveNthRoot(a: double, n: int) → double

Examples

Example 1

a = 9n = 2return = 3

The positive solution of r^2 = 9 is 3. A reported intermediate approximation of 2.99 is not the required answer at this practice tolerance.

Example 2

a = 1e-06n = 3return = 0.01

Since 0.01^3 = 0.000001, the positive root is 0.01.

Example 3

a = 32n = 5return = 2

Since 2^5 = 32, the positive fifth root is 2.

Constraints

  • 0.000001 <= a <= 1000000000000
  • 1 <= n <= 1000
  • a is a finite double-precision number and n is an integer.
  • Return a positive finite number satisfying |answer - r| <= 0.000001 * max(1, |r|).

More Akuna Capital problems

See Akuna Capital hiring insights
Saved
public double positiveNthRoot(double a, int n) {
    // write your code here
}
Checking account…