Tutorialspoint
Problem
Solution
Submissions

Number is a Power of Another Number

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to determine if a given number x is a power of another number y. In other words, check if there exists an integer n such that y^n = x.

Example 1
  • Input: x = 1024, y = 2
  • Output: true
  • Explanation:
    • 2^10 = 1024, so 1024 is a power of 2.
Example 2
  • Input: x = 100, y = 10
  • Output: true
  • Explanation:
    • 10^2 = 100, so 100 is a power of 10.
Constraints
  • 1 ≤ x ≤ 2^31 - 1
  • 1 ≤ y ≤ 2^31 - 1
  • Time Complexity: O(log x)
  • Space Complexity: O(1)
NumberVariables and Data TypesKPMGPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the property of logarithms to solve this problem.
  • Consider edge cases like x = 1 or y = 1.
  • Be careful about floating-point precision when using logarithms.
  • You can also use repeated division to check if y divides x perfectly until x becomes 1.

Steps to solve by this approach:

 Step 1: Handle the edge cases: if x is 1, return true; if y is 1, return true only if x is also 1.
 Step 2: If y is 0, return false (since 0 raised to any positive power is 0, not a positive x).
 Step 3: Use a while loop to repeatedly divide x by y as long as x is greater than 1.
 Step 4: Inside the loop, check if x is divisible by y. If not, return false.
 Step 5: If x is divisible by y, update x by dividing it by y.
 Step 6: After the while loop, check if x is equal to 1. If it is, return true; otherwise, return false.

Submitted Code :