C++程序:判断一个数是否为Proth数
给定一个数字'n',任务是确定给定的正整数是否为Proth数,并将结果显示为输出。
什么是Proth数?
Proth数由以下公式给出:
N=k⋅2n+1
其中,n 是一个正整数,k 是一个奇正整数。
前几个Proth数如下:
3, 5, 9, 13, 17, 25, 33, 41, 49, 57, 65, 81, 97.......
输入
number: 17
输出
its a proth number
输入
number: 18
输出
its not a proth number
程序中使用的算法如下:
输入要检查条件的数字。
应用给定的公式来检查它是否为Proth数。
如果条件成立,则打印它是Proth数。
如果条件不成立,则打印它不是Proth数。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
算法
Step 1→ declare function to calculate power of 2 bool isPower(int num) return (num && !(num & (num - 1))) Step 2→ Declare function to check if a number is a proth number or not bool isProth(int num) declare int k = 1 While (k < (num / k)) IF (num % k == 0) IF (isPower(num / k)) return true End Set k = k + 2 End End return false Step 3→ In main() Declare int num = 17 IF (isProth(num - 1)) Print "its a proth number" End Else Print "its not a proth number" End
示例
#include <bits/stdc++.h> using namespace std; //function to calculate power of 2 bool isPower(int num){ return (num && !(num & (num - 1))); } //function to check if a number is a proth number bool isProth(int num){ int k = 1; while (k < (num / k)){ if (num % k == 0){ if (isPower(num / k)) return true; } k = k + 2; } return false; } int main(){ int num = 17; if (isProth(num - 1)) cout << "its a proth number"; else cout << "its not a proth number"; return 0; }
输出
如果运行上述代码,它将生成以下输出:
its a proth number
广告