- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Given an integer 'n', check if it is a power of 3, and return True, otherwise False.
When it is required to check if a given variable is of power 3, a method named ‘check_power_of_3’ is defined that takes an integer as parameter. The modulus operator and the ‘//’ operator is used to check for the same and return True or False depending on the output.
Below is a demonstration of the same
def check_power_of_3(my_val): if (my_val == 0): return False while (my_val != 1): if (my_val % 3 != 0): return False my_val = my_val // 3 return True my_num = 81 print("The number to be checked is : ") print(my_num) if(check_power_of_3(my_num)): print(my_num, 'is a power of 3..') else: print(my_num, 'is not a power of 3..')
The number to be checked is : 81 81 is a power of 3..
A method named ‘check_power_of_3’ is defined that takes the number as a parameter.
If this value is 0, False is returned.
If it is not equal to 1, then the modulus operator is used with this integer to check if it returns 0, if not, it returns False.
Otherwise, the value is operated with 3 using the ‘//’ operator.
Outside the method, the number is defined and is displayed on the console.
The method is called by passing this number as a parameter.
The relevant output is displayed on the console.
- Python - Given an integer 'n', check if it is a power of 4, and return True, otherwise False.
- Why does php's in_array return true if passed a 0?
- Check whether product of 'n' numbers is even or odd in Python
- Is the popular saying 'Everything is an object in Java' true?
- Find whether a given integer is a power of 3 or not in C++
- Check if given number is a power of d where d is a power of 2 in Python
- Query Array for 'true' value at index n in MongoDB?
- What is difference between '.' , '?' and '*' in Python regular expression?
- Check if it is possible to create a palindrome string from given N in Python
- Check if it is possible to create a polygon with given n sidess in Python
- Can 'false' match some string in MySQL?
- How to determine if a variable is 'undefined' or 'null'?
- How do I check if raw input is integer in Python 3?