列印素數 兩種不同方法
阿新 • • 發佈:2022-12-06
1.用陣列列出素數表 是素數該下標對應的值為1 將每個素數的倍數對應的下標值賦為0 這樣就完成了素數表
#include <stdio.h> int main(){ const int maxNumber = 255; int isPrime[maxNumber]; int i; int x; for (int i = 0; i < maxNumber; ++i) { isPrime[i] = 1; } for (x = 2; x < maxNumber; ++x) { if(isPrime[x]){for ( i = 2; i*x<maxNumber; ++i) { isPrime[i*x] = 0; } } } for (i = 2; i < maxNumber; ++i) { if(isPrime[i]){ printf("%d\t",i); } } printf("\n"); return 0; }
2.用素數能否被之前的素數整除用來判斷
#include <stdio.h> int isPrime(intx,int knownPrimes[],int numberOfKnownPrimes){ int ret = 1; int i; for (i = 0; i < numberOfKnownPrimes; ++i) { if(x % knownPrimes[i] == 0){ ret = 0; break; } } return ret; } int main(){ const int number = 100; int prime[number] = {2};int count = 1; int i = 3; while (count < number) { if(isPrime(i, prime, count)){ prime[count++] = i; } i++; } for (i = 0; i < number; ++i) { printf("%d ", prime[i]); } printf("\n"); return 0; }