마크 B의 링크는 NSLogan이 작성한 정확하고 멋진 간단한 알고리즘을 보여줍니다. 나는 약간의 크기/속도 절충을 보여주기 위해 약간의 수정을했다. 나는 관심사로 나눌 줄 알았다.
우선, 코드 :
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <time.h>
#define USE_BITS
#ifdef USE_BITS
#define alloc_prime char *prime = calloc(i/8,sizeof(*prime));
#define set_not_prime(x) prime[x/8]|= (1<<(x%8))
#define is_prime(x) (!(prime[x/8]&(1<<(x%8))))
#endif
#ifdef USE_CHAR
#define alloc_prime char *prime = calloc(i,sizeof(*prime));
#define set_not_prime(x) prime[x] = 1
#define is_prime(x) (prime[x] == 0)
#endif
#ifdef USE_SIZE_TYPE
#define alloc_prime size_t *prime = calloc(i,sizeof(*prime));
#define set_not_prime(x) prime[x] = 1
#define is_prime(x) (prime[x] == 0)
#endif
int main(){
int i;
printf("Find primes up to: ");
scanf("%i",&i);
clock_t start, stop;
double t = 0.0;
assert((start = clock())!=-1);
//create prime list
alloc_prime;
int c1, c2, c3;
if(!prime){
printf("Can't allocate %zu bytes!\n",i*sizeof(*prime));
exit(1);
}
//set 0 and 1 as not prime
set_not_prime(0);
set_not_prime(1);
//find primes then eliminate their multiples (0 = prime, 1 = composite)
for(c2 = 2;c2 <= (int)sqrt(i)+1;c2++){
if(is_prime(c2)){
c1=c2;
for(c3 = 2*c1;c3 <= i+1; c3 += c1){
set_not_prime(c3);
}
}
}
stop = clock();
t = (double) (stop-start)/CLOCKS_PER_SEC;
//print primes
for(c1 = 0; c1 < i+1; c1++){
if(is_prime(c1))printf("%i\n",c1);
// if(prime[c1] == 0) printf("%i\n",c1);
}
printf("Run time: %f\n", t); //print time to find primes
return 0;
}
은 (USE_BITS 정의 할 때 정확한 없었던 오류 메시지 용서 ...)
I 부울 변수를 저장하는 세 가지 방법을 비교 했으므로 peoro가 제안했다. 한 가지 방법은 실제로 비트를 사용하고, 두 번째 방법은 전체 바이트를 사용하고 마지막 방법은 전체 기계 단어를 사용합니다. 각각의 flag/boolean이 여러분의 머신에 의해 더 자연스럽게 다루어지기 때문에 가장 빠른 것에 대한 순진한 추측은 머신 워드 방식 일 것입니다. 내 컴퓨터이었다에 다음과 같이 타이밍은 100,000,000까지 소수를 계산 :
비트 : 3.8s 숯을 : 5.8S M-단어 : 10.8s
그 추악한도 모두 흥미 롭다 하나의 비트만으로 부울을 나타내는 데 필요한 비트 시프 팅은 전체적으로 더 빠릅니다. 나의 추측은 캐싱과 locality-of-reference가 여분 ~ 3 지시를 능가하는 것 같다. 또한, n-bit-machine-word 방식의 메모리의 1/nth를 사용하게됩니다!
예, 직선 체는 느립니다. 지금까지 가지고있는 것을 게시하면 다른 사람이 개선 할 수 있도록 도와 줄 수 있습니다. – aschepler
코드를 게시하십시오. – Elalfer
5 초의 인터넷 검색 : http://www.dreamincode.net/code/snippet3315.htm –