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

更新於: 2020 年 1 月 17 日

114 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告