在 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