golang operator % not defined on float64

Viewed 3087

There's a leetcode test 326. Power of Three with a Mathematics method with java:

public class Solution {
    public boolean isPowerOfThree(int n) {
        return (Math.log(n) / Math.log(3) + epsilon) % 1 <= 2 * epsilon;
    }
}

When I intend to convert this solution to Golang Like

import "math"

func isPowerOfThree(n int) bool {
    return (math.Log10(float64(n)) / math.Log10(3)) % 1 == 0.0 
}

then here comes the compile error like

Line 4: Char 53: invalid operation: math.Log10(float64(n)) / math.Log10(3) % 1 (operator % not defined on float64) (solution.go)

I check the math package but there's no supported function like % operator, Is there any valid operator like % in Golang? thanks a lot :)

2 Answers

TLDR: _, frac := math.Modf(f)

You could use func Mod(x, y float64) float64 in math package.

package main

import (
    "math"
)

func isPowerOfThree(n int) bool {
    return math.Mod((math.Log10(float64(n)) / math.Log10(3)), 1.0) == 0.0 
}

You could also use func Modf(f float64) (int float64, frac float64).

package main

import (
    "math"
)

func isPowerOfThree(n int) bool {
    _, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
    return frac == 0.0
}

We can not use just below function, as there can be more than one digit after decimal in frac

_, frac := math.Modf((math.Log10(float64(n)) / math.Log10(3)))
return frac == 0.0

So to resolve this, use below logic

func isPowerOfThree(n int) bool { 
   quo,_ := math.Modf((math.Log10(float64(n)) / math.Log10(3))) 
   return n == int(math.Pow(3, quo)) 
} 
Related