Recursion: Power of three

Problem Statement:

You are given a number, return true if its a power of three else return false.

Example:

Input: n = 27
Output: true

Solution Recursive:

We can solve using recursive approach.

for each recursive call, value will be divided by 3.

Time Complexity: O(logn)
Space Complexity: O(logn)

Code Solution

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;


bool solution(int n) 
{
    if(n==0){
        return false;
    }
    else if(n==1){
        return true;
    }
    return n%3==0 && solution(n/3);  
}



int main() 
{
    int n = 9;
    
    if(solution(n))
    {
    	cout << "True" << endl;
    }
    else 
    {
        cout << "False" << endl;	
    }
    return 0;
}

Output

True
Write a Comment

Leave a Comment

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