Power of three and floating point numbers

To get the log3(n)log_3(n) in JavaScript, remember that:

log3(n)=log10(n)/log10(3)log_3(n) = log_{10}(n)/log_{10}(3)

You can define the previous expression in JavaScript:

javascript
Math.log3 = (n) => Math.log(n)/Math.log(3)

Let's assume now that n=27n = 27. Then:

javascript
Math.log3(27) // 3.0000000000000004

The result has an error, because of double-precision numbers. This can lead to errors when, for example, you want to check if n is a power of 3.

javascript
// 🔴 This will be incorrect because of double-precision numbers
var isPowerOfThree = (n) => {

    return Number.isInteger(Math.log3(n))

}

isPowerOfThree(27) // true

Solution

Calculate two candidates a, b (integers), and check if any of them is a power of three:

javascript
var isPowerOfThree = (n) => {

    if(n <= 0) return false

    let a = Math.floor(Math.log3(n))
    let b = Math.ceil(Math.log3(n))

    return (3 ** a === n) || (3 ** b === n)

}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.