C++程式:判斷一個數是否為Proth數
給定一個數字'n',任務是確定給定的正整數是否為Proth數,並將結果顯示為輸出。
什麼是Proth數?
Proth數由以下公式給出:
$$N=k\cdot\:2^{n}+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數。
演算法
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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP