Determine if a number, x, is a power of some other number y. Return the exponent. For example, for n = 9 and k = 3, return 2 because 3 to the power of 2 is 9. If n is not a power of k, return -1. I can't figure out how to return the exponent in this problem. Should I be using mod % ? Also, this problem requires a recursive solution.
function solution(x, y) {
if (x == 1)
return (y == 1);
let pow = 1;
while (pow < y)
pow = pow * x;
return solution(pow, y - 1);
};
console.log(solution(3, 9)); // should return 2 because 3 to the power of 2 is 9.
CodePudding user response:
use % to get the remainder, you can determine whether the remainder is 0 to determine the subsequent operation, I did not use recursion, but also the real output of the correct result, you see if it meets your requirements
function solution(x, y) {
if (y % x !== 0 || x > y) return -1
if (x === y) return 1
let i = 0
while (y % x === 0) {
i
y /= x
}
return i
}
console.log(solution(3, 9))