Q. Write a program to check if a given number is a power of three or not.
We are provided with a number as input and we need to check if the given number is a power of three or not.
For Example :-
n = 81
Output = Yes, 81 is a power of 3. (3^4 = 81)
Algorithm
To solve this problem, we can use the following algorithm: START Step 1 : Check if number is divisible by zero or not. If it return False then zero is not power of 3. Step 2 : If number if divisible by 3 then keep dividing the number by 3 until it is no longer divisible by three. Step 3 : After the loop end check if remaining number is 1 or not. If the remaining number is 1 then the number is a power of three. STOP
Program to check if a given number is a power of three or not
#include <stdio.h> int main() { int num; printf("Enter a number: "); scanf("%d", &num); while (num > 1) { if (num % 3 != 0) { printf("%d is not a power of three.\n", num); return 0; } num = num / 3; } printf("%d is a power of three.\n", num); return 0; }
#include <iostream> using namespace std; bool isPowerOfThree(int n) { if (n <= 0) { return false; } while (n % 3 == 0) { n /= 3; } return n == 1; } int main() { int n; cout << "Enter a number: "; cin >> n; if (isPowerOfThree(n)) { cout << n << " is a power of 3\n"; } else { cout << n << " is not a power of 3\n"; } return 0; }
public class PowerOfThree { public static boolean isPowerOfThree(int n) { if (n <= 0) { return false; } while (n % 3 == 0) { n /= 3; } return n == 1; } public static void main(String[] args) { int n = 27; if (isPowerOfThree(n)) { System.out.println(n + " is a power of three"); } else { System.out.println(n + " is not a power of three"); } } }
def isPowerOfThree(n): if n <= 0: return False while n % 3 == 0: n = n // 3 return n == 1
using System; public class Program { public static bool IsPowerOfThree(int n) { if (n <= 0) { return false; } while (n > 1) { if (n % 3 != 0) { return false; } n /= 3; } return true; } public static void Main() { int num = 27; if (IsPowerOfThree(num)) { Console.WriteLine($"{num} is a power of three"); } else { Console.WriteLine($"{num} is not a power of three"); } } }
#include <stdio.h> int main() { int num; printf("Enter a number: "); scanf("%d", &num); while (num > 1) { if (num % 3 != 0) { printf("%d is not a power of three.\n", num); return 0; } num = num / 3; } printf("%d is a power of three.\n", num); return 0; }
Output
27 is a power of three.
Recommended Programs
Program to reverse a string.Program to print fibonacci series.