Tutorialspoint
Problem
Solution
Submissions

Power of Three

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to check if a given integer is a power of three. An integer n is a power of three if there exists an integer i such that n = 3^i.

Example 1
  • Input: n = 27
  • Output: true
  • Explanation:
    1. We need to determine if 27 can be expressed as 3^i for some integer i.
    2. 27 = 3^3 (3 * 3 * 3 = 27)
    3. Since 27 can be expressed as 3^3, it is a power of three.
Example 2
  • Input: n = 0
  • Output: false
  • Explanation:
    1. 0 cannot be expressed as 3^i for any integer i.
    2. 3^i is always positive for any integer i.
    3. Therefore, 0 is not a power of three.
Constraints
  • -2^31 <= n <= 2^31 - 1
  • You must solve this without using loops or recursion
  • Time Complexity: O(1)
  • Space Complexity: O(1)
NumberVariables and Data TypesEYPhillips
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

  • Consider the properties of powers of three
  • In base-10, powers of three have specific patterns
  • Use mathematical properties to check if a number is a power of three
  • Consider that the largest power of three within the 32-bit signed integer range is 3^19 = 1162261467
  • Remember that only positive integers can be powers of three

Steps to solve by this approach:

 Step 1: First, handle the edge cases - negative numbers and zero cannot be powers of three.

 Step 2: Determine the largest power of three that fits within a 32-bit signed integer (3^19 = 1162261467).
 Step 3: Use the mathematical property that if n is a power of three, then the largest power of three (3^19) must be divisible by n.
 Step 4: This works because 3 is a prime number, so 3^19 only has factors that are powers of 3.
 Step 5: Check if 1162261467 % n == 0 to determine if n is a power of three.
 Step 6: This approach achieves O(1) time complexity without using loops or recursion.
 Step 7: Note that this method only works because 3 is prime. A similar approach for powers of non-prime numbers would require additional checks.

Submitted Code :