- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check whether number is a sum of powers of three in Python
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
Advertisements