代码需要使用c99编译
#include <stdio.h> #include <stdlib.h> #include <math.h> //是否为素数 //从2到x-1测试是否可以整除 //时间复杂度O(n-2),n趋向正无穷 int isPrime(int x) { int ret = 1; for(int i = 2; i < x; i++) { if(x % i == 0) { ret = 0; break; } } return ret; } //除了2以外,所有的偶数都不是素数,从3到x-1,每次加2 //x为偶数时间复杂度O((n-3)/2+1) //x很大时时间复杂度接近于(n/2) int isPrime2(int x) { int ret = 1; if(x == 1 || (x % 2 ==0 && x != 2)) ret = 0; for (int i = 3; i < x; i += 2) { if( x % i == 0) { ret = 0; break; } } return ret; } //无须到x-1,到sqrt(x) //时间复杂度O(Log2n) 即sqrt(x) int isPrime3(int x) { int ret = 1; if(x == 1 || x % 2 == 0 && x != 2) ret = 0; for(int i = 3 ; i < sqrt(x); i += 2) { if( x % i == 0) { ret = 0; break; } } return ret; } //判断是否能被已知的且<x的素数整除 int isPrime4(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(isPrime4(i ,prime, count)) { prime[count++] = i; } i++; } for( i = 0; i < number; i++) { printf("%d",prime[i]); if( (i + 1) % 5 ) printf("\t"); else printf("\n"); } return 0; }
原文地址:https://www.cnblogs.com/passedbylove/p/11332794.html
时间: 2024-10-28 19:08:53