Program to check whether number is a sum of powers of three in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n, we have to check whether it is possible to represent n as the sum of distinct powers of three or not. An integer y is said to be power of three if there exists an integer x such that y = 3^x.

So, if the input is like n = 117, then the output will be True because 117 = 3^4 + 3^3 + 3^2 + = 81 + 27 + 9.

To solve this, we will follow these steps −

  • for i in range 16 to 0, decrease by 1, do

    • if n >= 3^i , then

      • n := n - 3^i

  • if n > 0, then

    • return False

  • return True

Example

Let us see the following implementation to get better understanding −

def solve(n):
   for i in range(16, -1, -1):
      if n >= pow(3,i):
         n -= pow(3,i)

   if n > 0:
      return False

   return True

n = 117
print(solve(n))

Input

117

Output

True
raja
Published on 06-Oct-2021 11:07:25
Advertisements