Open In App

Find whether a given integer is a power of 3 or not

Improve
Improve
Like Article
Like
Save
Share
Report

Given a positive integer, write a function to find if it is a power of three or not. 
Examples: 

Input : 3
Output :Yes

Input :6
Output :No

General Solution to check if any number N is a power of P:

Refer to the code below for implementation. 

C++
#include <iostream>
using namespace std;
#include<math.h>  
int main()
{

    int b = 81;
    int a = 3;
    // computing power
    double p = log10(b) / log10(a);
    // checking to see if power is an integer or not
    if (p - (int)p == 0) {
        cout<<"YES";
    }
    else{
        cout<<"NO";
    }
    return 0;
}

// This code is contributed by ksrikanth0498.
C
// C program for the above approach
#include <stdio.h>
#include<math.h>  
int main() {
    int b = 81;
    int a = 3;
    // computing power
    double p = log10(b) / log10(a);
    // checking to see if power is an integer or not
    if (p - (int)p == 0) {
        printf("YES");
    }
    else{
        printf("NO");
    }
    
    return 0;
}
Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        int b = 81;
        int a = 3;
          // computing power
        double p = Math.log10(b)/ Math.log10(a); 
        // checking to see if power is an integer or not
        if (p - (int)p == 0) {
            System.out.println("YES");
        }
        else
            System.out.println("NO");
    }
}

/* This code is contributed by Ankit Agrawal */
Python3
# Python3 program for the above approach
import math
b = 81
a = 3
# computing power
p = math.log(b) / math.log(a)
# checking to see if power is an integer or not
if (p - int(p) == 0):
    print("YES")

else:
    print("NO")
C#
using System;

public class GFG{

     public static void Main()
    {
        int b = 81;
        int a = 3;
       
          // computing power
        double p = Math.Log10(b)/ Math.Log10(a); 
       
        // checking to see if power is an integer or not
        if (p - (int)p == 0) {
            Console.Write("YES");
        }
        else
            Console.Write("NO");
    }
}

// This code is contributed by laxmigangajula03.
Javascript
 <script>
 {
        let b = 81;
        let a = 3;
       
          // computing power
        let p = Math.log10(b)/ Math.log10(a); 
       
        // checking to see if power is an integer or not
        if(p - Math.floor(p) == 0) {
            document.write("YES");
        }
        else
            document.write("NO");
    }
    
    // This code is contributed by laxmigangarajula03
    </script>

Output
YES

Time Complexity: O(1)

Space Complexity: O(1)

Recursive approach :

Check if the number is divisible by 3, if yes then keep checking the same for number/3 recursively. If the number can be reduced to 1, then the number is divisible by 3 else not.

C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
bool isPower_of_Three(ll n)
{
    if (n <= 0)
        return false;
    if (n % 3 == 0)
        return isPower_of_Three(n / 3);
    if (n == 1)
        return true;
    return false;
}
int main()
{
    ll num1;
    num1 = 243;
    if (isPower_of_Three(num1))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    ll num2 = 6;
    if (isPower_of_Three(num2))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}

// This code is contributed by Sania Kumari Gupta (kriSania804)
C
#include <stdbool.h>
#include <stdio.h>

#define ll long long

bool isPower_of_Three(ll n)
{
    if (n <= 0)
        return false;
    if (n % 3 == 0)
        return isPower_of_Three(n / 3);
    if (n == 1)
        return true;
    return false;
}
int main()
{
    ll num1;
    num1 = 243;
    if (isPower_of_Three(num1))
        printf("Yes\n");
    else
        printf("No\n");
    ll num2 = 6;
    if (isPower_of_Three(num2))
        printf("Yes\n");
    else
        printf("No\n");
    return 0;
}

// This code is contributed by Sania Kumari Gupta (kriSania804)
Java
import java.util.*;

class GFG{
static boolean isPower_of_Three(long n)
{
    if (n <= 0)
        return false;
    if (n % 3 == 0)
        return isPower_of_Three(n / 3);
    if (n == 1)
        return true;
    return false;
}
  
  // Driver code
public static void main(String[] args)
{
    long  num1 = 243;
    if (isPower_of_Three(num1))
        System.out.print("Yes" +"\n");
    else
        System.out.print("No" +"\n");
    long num2 = 6;
    if (isPower_of_Three(num2))
        System.out.print("Yes" +"\n");
    else
        System.out.print("No" +"\n");
}
}

// This code is contributed by umadevi9616 
Python3
def isPower_of_Three(n):

    if (n <= 0):
        return False
    if (n % 3 == 0):
        return isPower_of_Three(n // 3)
    if (n == 1):
        return True
    return False

 # Driver code
num1 = 243
if (isPower_of_Three(num1)):
    print("Yes")
else:
    print("No")
    
num2 = 6
if (isPower_of_Three(num2)):
    print("Yes")
else:
    print("No")

# This code is contributed by shivanisinghss2110
C#
using System;

class GFG{
static Boolean isPower_of_Three(long n)
{
    if (n <= 0)
        return false;
    if (n % 3 == 0)
        return isPower_of_Three(n / 3);
    if (n == 1)
        return true;
    return false;
}
  
  // Driver code
public static void Main(String[] args)
{
    long  num1 = 243;
    if (isPower_of_Three(num1))
        Console.Write("Yes" +"\n");
    else
        Console.Write("No" +"\n");
    long num2 = 6;
    if (isPower_of_Three(num2))
        Console.Write("Yes" +"\n");
    else
        Console.Write("No" +"\n");
}
}

// this code is contributed by shivanisinghss2110
Javascript
<script>
function isPower_of_Three(n)
{
    if (n <= 0)
        return false;
    if (n % 3 == 0)
        return isPower_of_Three(n / 3);
    if (n == 1)
        return true;
    return false;
}

    
    let num1 = 243;
    if (isPower_of_Three(num1))
      document.write("Yes");
    else
          document.write("No");
    let num2 = 6;
    if (isPower_of_Three(num2))
      document.write("Yes");
    else
        document.write("</br>No");
        
        //This code is contributed by vaibhavrabadiyaa3.
</script>
PHP
<?php
    
  function isPower_of_Three($n)
{
    if ($n <= 0)
        return false;
    if ($n % 3 == 0)
        return isPower_of_Three($n / 3);
    if ($n == 1)
        return true;
    return false;
}

    
    $num1 = 243;
    if (isPower_of_Three($num1))
      echo("Yes");
    else
          echo("No"); 
    echo("\n");
    $num2 = 6;
    if (isPower_of_Three($num2))
      echo("Yes");
    else
        echo("No");
        
// This code is contributed by laxmigangarajula03
?>

Output
Yes
No

Time Complexity: O(log3n), where n represents the given integer.
Auxiliary Space: O(log3n).

Approach:
The logic is very simple. Any integer number other than power of 3 which divides highest power of 3 value that integer can hold 3^19 = 1162261467 (Assuming that integers are stored using 32 bits) will give reminder non-zero. 

C++
// C++ program to check if a number is power
// of 3 or not.
#include <iostream>
using namespace std;

// Returns true if n is power of 3, else false
bool check(int n)
{
    if (n <= 0)
        return false;
  
    /* The maximum power of 3 value that
       integer can hold is 1162261467 ( 3^19 ) .*/
    return 1162261467 % n == 0;
}

// Driver code
int main()
{
    int n = 9;
    if (check(n))
        cout <<"Yes";
    else
        cout <<"No";

    return 0;
}

// This code is contributed by shivanisinghss2110
C
// C++ program to check if a number is power
// of 3 or not.
#include <stdio.h>
#include <stdbool.h>

// Returns true if n is power of 3, else false
bool check(int n)
{
    if (n <= 0)
        return false;
    /* The maximum power of 3 value that
       integer can hold is 1162261467 ( 3^19 ) .*/
    return 1162261467 % n == 0;
}

// Driver code
int main()
{
    int n = 9;
    if (check(n))
        printf("Yes");
    else
        printf("No");

    return 0;
}
Java
// Java program to check if a number is power
// of 3 or not.
public class Power_3 {

    // Returns true if n is power of 3, else false
    static boolean check(int n)
    {
        /* To prevent
        java.lang.ArithmeticException: / by zero and
        negative n */
        if (n <= 0)
            return false;
        /* The maximum power of 3 value that
           integer can hold is 1162261467 ( 3^19 ) .*/
        return 1162261467 % n == 0;
    }

    // Driver code
    public static void main(String args[])
    {
        int n = 9;
        if (check(n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
// This code is contributed by Sumit Ghosh
Python
# Python program to check if a number is power
# of 3 or not.
 
# Returns true if n is power of 3, else false
def check(n):
    """ The maximum power of 3 value that 
       integer can hold is 1162261467 ( 3^19 ) ."""
    return 1162261467 % n == 0
 
# Driver code
n = 9
if (check(n)):
    print ("Yes")
else:
    print ("No")

# This code is contributed by Sachin Bisht
C#
// C# program to check if a number
// is power of 3 or not.
using System;

public class GFG {

    // Returns true if n is power
    // of 3, else false
    static bool check(int n)
    {
        if (n <= 0)
            return false;
        /* The maximum power of 3
        value that integer can hold
        is 1162261467 ( 3^19 ) .*/
        return 1162261467 % n == 0;
    }

    // Driver code
    public static void Main()
    {
        int n = 9;
        if (check(n))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}

// This code is contributed by
// nitin mittal.
Javascript
<script>
// Javascript program to check if a
// number is power of 3 or not.

// Returns true if n is
// power of 3, else false
function check(n)
{
    
    /* The maximum power of 3 value that
    integer can hold is 1162261467
    ( 3^19 ) . */
    return 1162261467 % n == 0;
}

    // Driver code
    let n = 9;
    if (check(n))
        document.write("Yes");
    else
        document.write("No");

// This code is contributed by nitin _saurabh_jaiswal
</script>
PHP
<?php
// PHP program to check if a 
// number is power of 3 or not.

// Returns true if n is 
// power of 3, else false
function check($n)
{
    
    /* The maximum power of 3 value that 
       integer can hold is 1162261467 
       ( 3^19 ) . */
    return 1162261467 % $n == 0;
}

    // Driver code
    $n = 9;
    if (check($n))
        echo("Yes");
    else
        echo("No");

// This code is contributed by nitin mittal
?>

Output
Yes

Time Complexity : O(1)

Auxiliary Space: O(1)
 

Approach:

This approach is based on the below simple observations.

Observation 1: If there is a power of three number, it will definitely end with either 3, 9 , 7 or 1.

Observation 2 : If a number ends with one of these 4 digits, we only have to check the powers of three which would guarantee a number ending with that last digit. For example, if a given number ends with 1, it must be a 4th or 8th or 12th and so on power of three, if at all.

Now since we are clear with the observations, let’s have a look at the algorithm.

Algorithm :  

Step 1: If the given number, n, is not ending with 3,9,7 or 1, it means that the number is not a power of three, therefore return FALSE.

Step 2: If not, we create a Map with 4 entries in it in order to maintain the mapping between the powers to three(1,2,3,4) and the number’s last digits(3,9,7,1).

Step 3: Extract the last digit from a given number and look up it’s corresponding power in the map.

Step 4:  If this power when raised to three equals  the number, n, return TRUE.

Step 5: If this power raised to three is less than the number, n, increment the power straight by 4 and loop step 4 until the power raised to three becomes more than n.  

Step 6: If the power raised to three becomes more than the given number, return FALSE.

C++
#include <bits/stdc++.h>
using namespace std;
bool isPowerOfThree(int n)
{
    if (n == 1)
        return true;
    int lastDigit = n % 10;
    map<int, int> map;
    map[3] = 1;
    map[9] = 2;
    map[7] = 3;
    map[1] = 4;

    if (!map[lastDigit])
        return false;

    int power = map[lastDigit];
    double powerOfThree = pow(3, power);
    while (powerOfThree <= n) {
        if (powerOfThree == n)
            return true;
        power = power + 4;
        powerOfThree = pow(3, power);
    }
    return false;
}
int main()
{
    int n = 81;
    cout << (isPowerOfThree(n) ? "true" : "false") << endl;
    n = 91;
    cout << (isPowerOfThree(n) ? "true" : "false") << endl;
    return 0;
}

// This code is contributed by umadevi9616
Java
/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class GFG {
    public static boolean isPowerOfThree(int n)
    {
        if (n == 1)
            return true;
        int lastDigit = n % 10;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(3, 1);
        map.put(9, 2);
        map.put(7, 3);
        map.put(1, 4);

        if (map.get(lastDigit) == null)
            return false;

        int power = map.get(lastDigit);
        double powerOfThree = Math.pow(3, power);
        while (powerOfThree <= n) {
            if (powerOfThree == n)
                return true;
            power = power + 4;
            powerOfThree = Math.pow(3, power);
        }
        return false;
    }
    public static void main(String[] args)
    {
        int n = 81;
        System.out.println(isPowerOfThree(n));
        n = 91;
        System.out.println(isPowerOfThree(n));
    }
}
Python3
'''package whatever #do not write package name here '''
def isPowerOfThree(n):
    if (n == 1):
        return True;
    lastDigit = n % 10;
    map =[0] * 1000;
    map[3] = 1;
    map[9] = 2;
    map[7] = 3;
    map[1] = 4;

    if (map[lastDigit] == None):
        return False;

    power = map[lastDigit];
    powerOfThree = pow(3, power);
    while (powerOfThree <= n):
        if (powerOfThree == n):
            return True;
        power = power + 4;
        powerOfThree = pow(3, power);
    
    return False;

if __name__ == '__main__':
    n = 81;
    print(isPowerOfThree(n));
    n = 91;
    print(isPowerOfThree(n));

# This code contributed by umadevi9616 
C#
/*package whatever //do not write package name here */
using System;
using System.Collections.Generic;

public class GFG {
    public static bool isPowerOfThree(int n)
    {
        if (n == 1)
            return true;
        int lastDigit = n % 10;
        Dictionary<int, int> map = new Dictionary<int,int>();
        map.Add(3, 1);
        map.Add(9, 2);
        map.Add(7, 3);
        map.Add(1, 4);

        if (!map.ContainsValue(lastDigit))
            return false;

        int power = map[lastDigit];
        double powerOfThree = Math.Pow(3, power);
        while (powerOfThree <= n) {
            if (powerOfThree == n)
                return true;
            power = power + 4;
            powerOfThree = Math.Pow(3, power);
        }
        return false;
    }
    public static void Main(String[] args)
    {
        int n = 81;
        Console.WriteLine(isPowerOfThree(n));
        n = 91;
        Console.WriteLine(isPowerOfThree(n));
    }
}

// This code is contributed by umadevi9616
Javascript
<script>
/*package whatever //do not write package name here */    
function isPowerOfThree(n) {
        if (n == 1)
            return true;
        var lastDigit = n % 10;
        var map = new Map();
        map.set(3, 1);
        map.set(9, 2);
        map.set(7, 3);
        map.set(1, 4);

        if (map.get(lastDigit) == null)
            return false;

        var power = map.get(lastDigit);
        var powerOfThree = Math.pow(3, power);
        while (powerOfThree <= n) {
            if (powerOfThree == n)
                return true;
            power = power + 4;
            powerOfThree = Math.pow(3, power);
        }
        return false;
    }

    // Driver code
        var n = 81;
        document.write(isPowerOfThree(n)+"<br/>");
        n = 91;
        document.write(isPowerOfThree(n));

// This code is contributed by umadevi9616 
</script>

Output
true
false

Analysis:

Runtime Complexity:

O(1): Since the given number is an Integer, it can at max be 2147483647 (32 bit) and the highest power of three that is less than or equal to this number is 3^19 = 1162261467. And since we increment the power by 4, we will have a loop running at most 5 times, hence O(1).

Space Complexity:

O(1): Since we only have 4 entries in a Map no matter how big the number is given to us. 

Method 5: Using math module and is_integer 

1. The function ‘is_power_of_3(n)’ takes an integer ‘n’ as input and returns True if ‘n’ is a power of 3, and False otherwise.

2. The function first checks if the input is less than or equal to 0. If so, it returns False because 0 and negative numbers cannot be powers of 3.

3. If the input is greater than 0, the function computes the logarithm of the input with base 3 using the ‘math.log(n, 3)’ function. 

4. If the logarithm is an integer, then the input is a power of 3 and the function returns True. If the logarithm is not an integer, then the input is not a power of 3 and the function returns False. 

For example, if we call ‘is_power_of_3(9)’, the function will return True because the logarithm of 9 with base 3 is 2, which is an integer.

C++
// C++ program for the above approach        
#include <iostream>
#include <cmath>

using namespace std;

// Checking whether a given integer is a power of 3 or not
bool isPowerOf3(int n) {
    if (n <= 0) {
        return false;
    }
    return fmod(log(n) / log(3), 1) == 0;
}

int main() {
    cout << boolalpha;
    cout << isPowerOf3(9) << endl;   // true
    cout << isPowerOf3(27) << endl;  // true
    cout << isPowerOf3(45) << endl;  // false
    return 0;
}
// Contributed by adityasha4x71
Java
import java.lang.Math;

class Main { 
  // Checking whether a given integer is a power of 5 or not
    static boolean isPowerOf3(int n) {
        if (n <= 0) {
            return false;
        }
        return Math.log(n) / Math.log(3) % 1 == 0;
    }

    public static void main(String[] args) {
        System.out.println(isPowerOf3(9)); // true
        System.out.println(isPowerOf3(27)); // true
        System.out.println(isPowerOf3(45)); // false
    }
}
Python3
import math

def is_power_of_3(n):
    if n <= 0:
        return False
    return math.log(n, 3).is_integer()
print(is_power_of_3(9))
print(is_power_of_3(27)) 
print(is_power_of_3(45))
C#
using System;

public class GFG {
    static bool IsPowerOf3(int n) {
        if (n <= 0)
            return false;
        return Math.Log(n, 3) % 1 == 0;
    }

    static void Main() {
        Console.WriteLine(IsPowerOf3(9)); // Output: True
        Console.WriteLine(IsPowerOf3(27)); // Output: True
        Console.WriteLine(IsPowerOf3(45)); // Output: False
    }
}
Javascript
// Javascript program to check if a
// number is power of 3 or not.

// Checking Function whether a given integer is a power of 3 or not
function isPowerOf3(n) {
  if (n <= 0) {
    return false;
  }
  return Math.log(n) / Math.log(3) % 1 === 0;
}
// Giving Output on Conole based
console.log(isPowerOf3(9)); // true
console.log(isPowerOf3(27)); // true
console.log(isPowerOf3(45)); // false

// This Code is Contributed by Vikas Bishnoi

Output
true
true
false

Time Complexity: O(log n) 
Auxiliary Space: O(1) 

This approach is contributed by Durgesh Valecha.

Method 5: Iterative Solution

Approach : Divide the input by 3 ,until it is divisible by 3. If number left is 1 after the loop ends then the input is a power of 3 else not.

C++
#include <iostream>
using namespace std;

string isPowerof3(int N) {
    while (N % 3 == 0) {
        N /= 3;
    }
    if (N == 1) {
        return "Yes";
    } else {
        return "No";
    }
}

int main() {
    int n = 9;
    string ans = isPowerof3(n);
    cout << ans << endl;
    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
      public static String isPowerof3(int N){
        while(N%3==0){
            N/=3;
        }        
        if(N==1)
            return "Yes";
        else
            return "No";
    }
    public static void main (String[] args) {
          int n = 9;
        String ans = isPowerof3(n);
        System.out.println(ans);
    }
}
Python
# code
def is_power_of_3(N):
    while N % 3 == 0:
        N //= 3
    if N == 1:
        return "Yes"
    else:
        return "No"

if __name__ == "__main__":
    n = 9
    ans = is_power_of_3(n)
    print(ans)
C#
using System;

public class GFG{
      public static string IsPowerof3(int N)
    {
        while (N % 3 == 0)
        {
            N /= 3;
        }
        if (N == 1)
        {
            return "Yes";
        }
        else
        {
            return "No";
        }
    }

    static public void Main (){
        int n = 9;
        string ans = IsPowerof3(n);
        Console.WriteLine(ans);
        // Code
    }
Javascript
function isPowerof3(N) {
    while (N % 3 === 0) {
        N /= 3;
    }
    if (N === 1) {
        return "Yes";
    } else {
        return "No";
    }
}

const n = 9;
const ans = isPowerof3(n);
console.log(ans);

Output
Yes

Output :

Yes

Time Complexity: O(log n) 

Auxiliary Space: O(1) 

Method 6: Bit Manipulation

This method utilizes bitwise left shift operator to check if a given number is a power of three.

  1. We uses a while loop to perform a bitwise left shift on temp and adds the result to temp until temp becomes greater than or equal to the input n.
  2. Bitwise left shift mimics the pattern of powers of 3, where each shift corresponds to the next power of 3.
  3. The loop continues while n is greater than 1 and temp is less than n.
  4. Returns true if temp is equal to the input n otherwise, it returns false.
C++
#include <bits/stdc++.h>
#define ll long long
using namespace std;
bool isPower_of_Three(ll n)
{
  ll temp=1;
  int i=1;
  while(n>1 && temp<n){
    temp+=temp<<1;
    }
  return temp==n;
}
int main()
{
    ll num1;
    num1 = 243;
    if (isPower_of_Three(num1))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    ll num2 = 6;
    if (isPower_of_Three(num2))
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}

Output
Yes
No

Time Complexity: O(logn)

Space Complexity: O(1)




Last Updated : 27 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads