C 程式設計中的超級素數


超級素數是一種在所有素數序列中佔據素數位置的數。也被稱為高階素數,這些數在素數序列中佔據的位置等於素數。一些超級素數有 3、5、11、17…

例如,讓我們找出小於 13 的所有超級素數 -

輸入 

13

輸出

3, 5, 11.

說明 − 要找到小於 13 的超級素數,我們將找出所有小於 13 的素數。因此,顯示所有小於 13 的素數為 2、3、5、7、11、13。現在,2 是一個素數,因此我們將把位置 s 的素數視為超級素數。這意味著三是一個素數。類似地,位於位置 3 的 5 和位於位置 5 的 11 是超級素數。

要找出所有小於給定素數的所有超級素數,首先將找出所有小於該數的素數,然後將它們儲存在陣列中。從這個陣列中,我們將僅列印那些其位置等於任何素數的數。例如,位置為第 2 個、第 3 個、第 5 個、第 7 個、第 11 個、第 13 個等的素數被考慮在內。

示例

#include<iostream>
using namespace std;
bool SieveOfEratosthenes(int n, bool isPrime[]) {
   isPrime[0] = isPrime[1] = false;
   for (int i=2; i<=n; i++)
      isPrime[i] = true;
   for (int p=2; p*p<=n; p++) {
      if (isPrime[p] == true) {
         for (int i=p*2; i<=n; i += p)
            isPrime[i] = false;
      }
   }
}
void superPrimes(int n) {
   bool isPrime[n+1];
   SieveOfEratosthenes(n, isPrime);
   int primes[n+1], j = 0;
   for (int p=2; p<=n; p++)
      if (isPrime[p])
   primes[j++] = p;
   for (int k=0; k<j; k++)
      if (isPrime[k+1])
   cout << primes[k] << " ";
}
int main() {
   int n = 343;
   cout << "Super-Primes less than "<< n << " are :"<<endl;
   superPrimes(n);
   return 0;
}

輸出

Super-Primes less than 343 are :
3 5 11 17 31 41 59 67 83 109 127 157 179 191 211 241 277 283 331

更新時間:2019 年 8 月 13 日

1K+ 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始吧
廣告