Time complexity of a function which check if a number is power of two numbers

Ashvin Sharma :

I wrote a solution to check if a number(N) can be represented as

eq

where A > 0 and P > 1. I think the complexity of this solution is O(complexity)

But I am not sure about the base of the log and I do not have a mathematical explanation, I just understand the working of the loop which helped me come to my conclusion.

public int isPower(int A) {
    for (int i = 2; i <= Math.sqrt(A); i++) {
        for (int j = 2; j <= (Math.log(A) / Math.log(i)); j++) {
            if ((int)Math.pow(i, j) == A)
                return 1;
        }
    }
    return (A == 1) ? 1: 0;
}

I am preparing for interviews and any solution would be greatly appreciated and will help me prepare better. Also if you think this problem can be done faster than my algorithm let me know.

Abhishek Garg :

Thanks for correcting the solution Ashwin.

You don't need to iterate the second loop completely again and can do only one value check. The sample code will look like this.

public int isPower(int a) {
        if (a == 1) {
            return 1;
        }
        for (long i = 2; i * i <= a; i++) {
            final double value = Math.log(a) / Math.log(i);
            if (value - (int) value < 0.00000001) {
                return 1;
            }
        }
        return 0;
    }

The complexity of this solution O(sqrt(n)). I think this is the most efficient solution.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132594&siteId=1