cprimes

Finding Primes, where did I got wrong?


So...it works for small numbers but if temp is bigger than 1000, it just print 0 or random number...

#include <stdio.h>

int main() {
    int primes[10001];
    primes[10000] = 0;
    int i,temp;
    int n = 2;
    temp = 0;
    while(temp<=1000){
        for(i=2; i<n; i++){
            if(n%i == 0){
                goto Exit;
            }
        }primes[temp] = n; temp ++;
        Exit:
        n ++;
    }
    for(i=0; i<10001; i++){
        printf("%d\n",primes[i]);
    }
    return 0;
 }

Solution

  • The 1,000th prime is 7919. The 10,000th prime is 104,729. On some systems, an int is 16 bits (65,535). This is big enough for 1,000 primes, but not for 10,000 primes. Try changing all your int variables to long variables.