Want to find whether a given integer is a power of 3 or not in c++ programming language. Any integer number other than power of 3 which divides highest power of 3 value that integer can hold 3^19 = 1162261467 will give reminder non-zero.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /** * C++ program to check if a number is power of 3 or not. */ #include <stdio.h> // Returns true if n is power of 3, else false bool check(int n) { /* The maximum power of 3 value that integer can hold is 1162261467 ( 3^19 ) .*/ return 1162261467 % n == 0; } int main() { int n = 9; if (check(n)) printf("Yes"); else printf("No"); return 0; } |
Program Output
1 | Yes |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.