Search code examples
c#mathexponentiation

C# isPowerOf function


I have the next function:

static bool isPowerOf(int num, int power)
{
        double b = 1.0 / power;
        double a = Math.Pow(num, b);
        Console.WriteLine(a);
        return a == (int)a;
}

I inserted the print function for analysis.

If I call the function:

isPowerOf(25, 2)

It return true since 5^2 equals 25. But, if I call 16807, which is 7^5, the next way:

isPowerOf(16807, 5)

In this case, it prints '7' but a == (int)a return false.

Can you help? Thanks!


Solution

  • Try using a small epsilon for rounding errors:

    return Math.Abs(a - (int)a) < 0.0001;
    

    As harold suggested, it will be better to round in case a happens to be slightly smaller than the integer value, like 3.99999:

    return Math.Abs(a - Math.Round(a)) < 0.0001;