Search for a command to run...
Exact integer root, or -1 if there is none
Initialization
Look for an integer x with x^3 = 27, searching candidates 1…27.
Binary Search on the Answer
1function helperFunc(mid, n, m) {2 let ans = 1, base = mid;3 4 // Fast exponentiation, bailing out early5 while (n > 0) {6 if (n % 2 === 1) {7 ans *= base;8 if (ans > m) return 2; // overshoots9 n--;10 } else {11 n = Math.floor(n / 2);12 base *= base;//N: 3M: 27low: 1high: 2713 if (base > m) return 2;14 }15 }16 if (ans === m) return 1; // exact17 return 0; // too small18}19 20function NthRoot(N, M) {21 let low = 1, high = M;22 23 while (low <= high) {24 const mid = Math.floor((low + high) / 2);25 const midN = helperFunc(mid, N, M);26 27 if (midN === 1) return mid;28 else if (midN === 0) low = mid + 1;29 else high = mid - 1;30 }31 return -1;32}