I've got this piece of code that would print prime numbers up to the screen.
For example, printPrimes(500000) would fill the screen w开发者_高级运维ith all prime number's up to the 500000th one (which is 7368787).
Problem is, passing a larger number like 600000 or 1000000 would break the program.
Any ideas? Thanks in advance.
typedef enum {false, true} bool;
bool isPrime(long number, long primes[], long n) {
int divisor, index;
for (index = 0; index < n; ++index) {
divisor = primes[index];
if (divisor * divisor > number) {
return true;
} else if (number % divisor == 0) {
return false;
}
}
return 0;
}
void printPrimes(long n) {
long primes[n];
long odd, index;
primes[0] = 2;
odd = 1;
index = 1;
while (index < n) {
odd += 2;
if (isPrime(odd, primes, n)) {
printf("%ld ", odd);
primes[index] = odd;
++index;
}
}
}
Here:
long primes[n];
You are overflowing the stack if n
is large enough (the stack is quite small). Try using malloc
instead.
long *primes = malloc(sizeof(*primes) * n);
精彩评论