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(int x,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; }
标签:maxNumber,两种,int,打印,number,++,素数,isPrime From: https://www.cnblogs.com/xinrenbool/p/16953699.html