Python - Given an integer 'n', check if it is a power of 3, and return True, otherwise False.

PythonServer Side ProgrammingProgramming

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.

Example

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..')

Output

The number to be checked is :
81
81 is a power of 3..

Explanation

  • 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.

raja
Published on 20-Sep-2021 11:13:54

Advertisements