Given an integer 'N', you need to determine whether the given integer is a power of 3 or not.
The first line of input contains an integer βTβ representing the number of test cases.
The first and the only line of each test case contains the integer βNβ denoting the number.
Output Format:
For each test case, on a separate line, output one integer 0 or 1. Print 1, if N is a power of 3, or 0 otherwise.
Print the output of each test case in a separate line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^9
Time limit: 1 sec
2
81
6
1
0
For the first test case, 81 = 3^4. So, return 1.
For the second test case, 6 = 2 * 3^1. So, return 0.
2
27
1
1
1
For the first test case, 27 = 3^3. So, return 1.
For the second test case, 1 = 3^0. So, return 1.
Use basic maths.
Approach: The idea here is to keep dividing βNβ by 3 every time till βNβ is divisible by 3. If at the end N is greater than 1 then the number will not be divisible by 3.
The algorithm is as follows :
O(logN), where N is the given number.
Here we are dividing N every time by 3, which is of the order logN base 3. So, the overall time complexity is O(logN).
O(1),
As are using constant extra space.