- 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
Power of Three in Python
Suppose we have a number n. We have to check whether the number is the power of 3 or not. So if the number is like n = 27, that is the power of 3, the result will be true, if n = 15, it will be false.
To solve this, we will follow these steps −
- We will use the Logarithm to solve this
- if [log10(n) / log10(3)] mod 1 == 0, then it will be power of three, otherwise not
Example
Let us see the following implementation to get a better understanding −
class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ if not n or n<0: return False return (math.log10(n)/ math.log10(3)) % 1 == 0 ob1 = Solution() print(ob1.isPowerOfThree(27)) print(ob1.isPowerOfThree(15)) print(ob1.isPowerOfThree(9)
Input
27 15 9
Output
true false true
Advertisements