Write a C++ programming to check if a given integer is a power of three or not

  • برمجة سي بلس بلس
  • برمجة

Write a C++ programming to check if a given integer is a power of three or not

Input: 9
Output: true
Input: 81
Output: true
Input: 45
Output: false

Sample Output:

If 15 is power of three? False

If 9 is power of three? True

If 243 is power of three? True

الأجوبة

#include <iostream>
using namespace std;

string is_PowerOf_Three(int n) {
        while (n % 3 == 0) {
            n = n / 3;
        }

        if (1 == n) {
            return "True";
        } else {
            return "False";
        }
    }

int main(void)
{
    int n = 15;
    cout << "\nIf " << n << " is power of three? " << is_PowerOf_Three(n) << endl; 
    n = 9;
    cout << "\nIf " << n << " is power of three? " << is_PowerOf_Three(n) << endl; 
    n = 243;
	cout << "\nIf " << n << " is power of three? " << is_PowerOf_Three(n) << endl; 
    return 0;   
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...