# Program to store 1000 prime numbers in an array and print out every 15th

This is a discussion on Program to store 1000 prime numbers in an array and print out every 15th within the C Programming forums, part of the General Programming Boards category; This is a program to put the first 1000 numbers in an array and print out every 15th. It compiles ...

1. ## Program to store 1000 prime numbers in an array and print out every 15th

This is a program to put the first 1000 numbers in an array and print out every 15th. It compiles but the program crashes.

Code:
```#include <stdio.h>
int main ()
{
int array[1000];

int a=0;
int num1=2;
int num2=0;
int b = 0;

printf("These are every 15th prime number up to the 1000th prime:\n\n");

while (b < 1000){

while ( num1 < b ){

if ( b%num2 == 0){

num2++;
}

num1++;
}

if (num2 == 0){

array[b] = b;
}
b++;
}
b=0;

while (b<=1000){

printf("%d\n",array[b]);

b+15;

}

return 0;
}```

2. I would first find every prime number you need, and then use an if statement ONLY in the printing block of code, to allow printing every 15th number in the prime array. In your printing loop:

Code:
```if(i % 15==0 && i)
printf("%d", primes[i]);```
In general, while() loops are not as good when you're working out logic for a program. For loops just set your mind right to solve the looping problems.

Code:
```   Handle the two prime number in here,
since it's the only even prime number.

for(primeCnt =0;primeCnt<1000;primeCnt++) {

for(testNum = 3,flag=1;;testNum+=2) { //skip the even numbers

for(n=3;n*n<=testNum;n+=2) { //start the testing loop
with the modulus operator % if the answer is ever 0
then testNum is a composite number, so break out of
the test loop, after setting a flag to 0.

}
if a number has a flag of 1 still, then it's a prime
number. Check your flag.
}
}```
Too much going on here to use while loops comfortably. I know you can do it, but there's a reason why for loops are the most popular kind of loop.

This is the "trial by division" algorithm. There are others, like the Sieve of Eratosthenes, which are even faster. Wiki has info on them all.

Popular pages Recent additions