Program to Check if the Given Number is Power of 3 (K) | Python, C/C++

Program to Check if the Given Number is Power of 3 (K) | Python, C/C++

Problem statement:

Write a Python, C/C++ program to check if the given number is the power of 3 (k- any other integer number).

Example:

The numbers which are the power of three: 3 (3^1), 9 (3^2), 27 (3^3), 81 (3^4), etc.
The numbers which are not the power of three: 2, 4, 5, 6, 18.

Note: Some number that is divisible by three not necessarily to be the power of three. Example: 18, 36

Program to Check if the Given Number is Power of 3 (K)

Algorithm:

  1. If the n==k and k==1, given number (n) is the power of k. Return true.
  2. If n is not divisible by k, given number (n) is not a power of k. Return false.
  3. Repeat steps 1 and 2 where n=n/k.

Python Code

Prerequisite:

Python Program:

def isPowerOf(n, k):
  if n==k or n==1:
    return True
  n=n/k
  if not n.is_integer():
    return False
  else:
    return isPowerOf(n, k)

#check the numbers
print(isPowerOf(10, 3))
print(isPowerOf(15, 2))
print(isPowerOf(64, 4))
print(isPowerOf(27, 3))
print(isPowerOf(81, 3))

Output:

False
False
True
True
True

You can also take the ‘n’ and ‘k’ values as user input in Python.

C/C++ Code

Prerequisite:

C/C++ Program:

#include <stdio.h>

#define TRUE 1
#define FALSE 0

int isPowerOf(int n, int k)
{
  if(n==k || n==1)
    return(TRUE);
  if(n%k)
    return(FALSE);
  else
    return isPowerOf(n/k, k);
}

//driver function for testing
void testFunction(int n, int k)
{
  int out = isPowerOf(n, k);
  if(out)
    printf("%d is power of %d\n", n, k);
  else
    printf("%d is not power of %d\n", n, k);
}
void main()
{
  testFunction(10, 3);
  testFunction(15, 2);
  testFunction(64, 4);
  testFunction(27, 3);
  testFunction(81, 3);
}

Output:

10 is not power of 3
15 is not power of 2
64 is power of 4
27 is power of 3
81 is power of 3

This is one of the most common coding questions asked in a placement interview. Try to solve these different programming languages like Python, C/C++, Java. The logic remains the same.

Leave a Reply

Your email address will not be published. Required fields are marked *