In this problem, we are asked to determine if a number y is a power of another number x. Formally, we want to know if there exists an integer n ≥ 0 such that: xn=y

This problem often comes up in coding interviews and requires careful handling of edge cases.

Problem Examples

Example 1

Input: x = 2, y = 8
Output: true

Example 2

Input: x = 1, y = 8
Output: false

Example 3

Input: x = 46, y = 205962976
Output: true

Key Observations

  1. If y == 1, the answer is always true because (x^0 = 1) for any positive integer x.

  2. If x == 1, then (1^n = 1) only. So y must be exactly 1.

  3. For general cases, we can keep multiplying x until the result is greater than or equal to y.

  4. If we reach y exactly while multiplying, y is a power of x. Otherwise, it is not.

Java Implementation

class Solution {
    public boolean isPower(int x, int y) {
        // Step 1: Handle edge cases
        if (y == 1) return true;       // x^0 = 1
        if (x == 1) return y == 1;     // Only 1^n = 1

        long curr = 1;  // Use long to avoid integer overflow

        // Step 2: Multiply x repeatedly until curr >= y
        while (curr < y) {
            curr *= x;
        }

        // Step 3: Check if we exactly reached y
        return curr == y;
    }
}

How the Code Works

Step 1: Edge Cases

if (y == 1) return true;
if (x == 1) return y == 1;

Step 2: Iterative Multiplication

long curr = 1;
while (curr < y) {
    curr *= x;
}

Step 3: Check Result

return curr == y;

Examples with Output

xyOutputExplanation
28true(2^3 = 8)
18false(1^n) never equals 8
46205962976true(46^5 = 205962976)
50312500000true(50^5 = 312500000)
51true(5^0 = 1)

Complexity Analysis

Conclusion

This solution efficiently checks if a number y is a power of x, handles edge cases properly, and avoids overflow issues by using long.