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