在 C++ 中查詢給定的整數是否是 3 的冪
在這個問題中,我們給定一個整數 N。我們的任務是找出給定的整數是否是 3 的冪。
我們舉個例子來理解這個問題,
Input : N = 729 Output : Yes
說明 −
36 = 719
解決方案方法
這個問題的解決方案是檢查 3 的冪的值。我們將檢查給定的數字 N 是否除以 1162261467 (319)。如果它是 3 的冪,則餘數將為 0,即 N 將除以它。如果不是,則該數字不是 3 的冪。
示例
程式來說明我們解決方案的工作原理
#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;
}輸出
The number is a power of 3
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP