# Thread: prime pairs from 3 - 10,000

1. ## prime pairs from 3 - 10,000

i found a set of beginner's problems to solve...i came up with a solution to this one:

print out all the prime pairs (prime numbers that differ only by 2) from 3 - 10,000.

Code:
```#include <stdio.h>
#include <stdlib.h>

main(){
int this_number, divisor, not_prime;
int array[1500];
int position = 0;
this_number = 3;

while(this_number < 10000){
divisor = this_number / 2;
not_prime = 0;
while(divisor > 1){
if(this_number % divisor == 0){
not_prime = 1;
divisor = 0;
}
else
divisor = divisor-1;
}
if(not_prime == 0) {
array[position] = this_number;
position = position + 1;
}
this_number = this_number + 1;
}
position = 0;
while (position < 1500) {
if ((array[(position + 1)] - array[position]) == 2) {
printf ("%d and %d are prime pairs.\n", array[position], array[(position + 1)]);
}
position = position + 1;
}
getchar();
exit(EXIT_SUCCESS);
}```

anybody have any ideas how i could more 'correctly' do this? for instance...i chose 1500 as the array size to ensure it would be big enough. could i implement some sort of counter that holds the number of primes found, and then automatically set the array size to that value?

2. I don't know if this approach is better or more correct than your approach but it's different.

Code:
```#include <stdio.h>
#include <malloc.h>

int main(void)
{
int this_number = 3, position = 0,divisor, not_prime, index;
int *array = NULL;

while(this_number < 10000)
{
divisor =  this_number >> 1;
not_prime = 0;
while(divisor > 1)
{
if(!(this_number % divisor))
{
divisor = !divisor;
not_prime = 1;
}
else
divisor -= 1;
}
if(!not_prime)
{
if(!position)
array =  malloc(sizeof(int) * 1);
else
realloc(array, sizeof(int) * position+1);
array[position] = this_number;
position +=1;
}
this_number += 1;
}
for(index = 0; index < position; index++ )
{
if(*(array+index+1) - *(array+index) == 2)
{
printf ("%d and %d are prime pairs.\n",*(array+index) ,*(array+index+1) );
}
}
if(array)
free(array);
return 0;
}```

3. Code:
`#include <malloc.h>`
*Ahem* Mr. Rip Van Winkle, it's been 20 years, but you may want to use the correct header.
Code:
`realloc(array, sizeof(int) * position+1);`

Checking return values is always something we like to encourage here.

And my linter doesn't like this either.
Code:
`divisor =  this_number >> 1;`

4. I stand corrected on the headers. Normally, I check all returns to keep the QA folks happy. Here on the forum, I thought I could get away with posting sloppy code. Mostly because I get a little lazy and just don't feel like writing all the additional code. I was wrong. This forum is a lot tougher than the QA types.

I'll just have to be more concientious in the future.

Thanx

Bob

5. We tend to post with the -pedantic flag whenever possible.

Quzah.