C++ 中列印所有不超過 N 的 Proth 素數
此題中,提供了一個整數 N,要求打印出小於或等於 N 的所有proth 素數。
Proth 素數
proth 素數為正整數,其值可表示為 n = k* 2n + 1。其中 k 是一個奇正整數,n 是一個正整數,且兩者均滿足 2n > k。
示例 − 3、5、13……
我們舉個例子,以更好地理解此主題 −
Input: N = 23 Output: 3, 5, 13, 17.
為此,我們將找到所有小於 N 的素數(為此我們將使用埃拉託斯特尼篩法)。然後檢查每個素數是否為proth 數。並打印出所有 proth 數。
示例
#include <bits/stdc++.h>
using namespace std;
int prime[1000];
void SieveOfEratosthenes(int n){
for (int i = 1; i <= n + 1; i++)
prime[i] = true;
prime[1] = false;
for (int p = 2; p * p <= n; p++) {
if (prime[p] == true) {
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
bool isTwosExponent(int n){
return (n && !(n & (n - 1)));
}
bool isaProthNumber(int n){
int k = 1;
while (k < (n / k)) {
if (n % k == 0) {
if (isTwosExponent(n / k))
return true;
}
k = k + 2;
}
return false;
}
bool isaProthPrime(int n){
if (isaProthNumber(n - 1)) {
if(prime[n])
return true;
else
return false;
}
else
return false;
}
int main(){
int n = 23;
cout<<"Proth Prime Numbers less than or equal to "<<n<<" are :\n";
SieveOfEratosthenes(n);
for (int i = 1; i <= n; i++)
if (isaProthPrime(i))
cout<<i<<"\t";
return 0;
}輸出
小於或等於 23 的 Proth 素數為 −
3 5 13 17
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP