-1

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.

1 Answers1

1

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))
Ccclot
  • 26
  • 2
  • Thank you, this works to get me started towards a recursive solution!! I'm curious and it might be obvious but why are we returning i? – Sharon Kaufman Jan 17 '23 at 02:52
  • @SharonKaufman - why would you accept code that doesn't meet your requirements of recursive code - granted, recursion is not at all required for this, but ... – Jaromanda X Jan 17 '23 at 02:55