
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If an Integer Is a Power of 3 in C++
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
Explanation −
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.
Example
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"; else cout<<"The number is not a power of 3"; return 0; }
Output
The number is a power of 3
Advertisements