Find whether a given integer is a power of 3 or not in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integer N. Our task is to find whether a given integer is a power of 3 or not.

Let's take an example to understand the problem,

Input : N = 729
Output : Yes


36 = 719

Solution Approach

A solution to the problem is by checking for the value that is power of 3. We will check if the given number N divides 1162261467 (319). If it is a power of 3, the remainder with be 0 i.e. N will divide it. If it does not, the number is not the power of 3.


Program to illustrate the working of our solution

#include <iostream>
using namespace std;
bool isPowerOf3(int n){
   if (n <= 0)
      return false;
   return 1162261467 % n == 0;
int main(){
   int n = 27;
   if (isPowerOf3(n))
      cout<<"The number is a power of 3";
      cout<<"The number is not a power of 3";
   return 0;


The number is a power of 3
Updated on 01-Feb-2022 08:04:05