Can you help with a program I'm trying to do in C.  I basically need a function that returns a the first 20 postive prime numbers.
###### Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x

Commented:
#include <stdio.h>
#define TRUE 1
#define FALSE 0
void getPrimes(long numPrimes, long *primes);

void main(void)
{
long primes[20];
long i;

getPrimes(20,primes);
for(i = 0;i<20;i++)
{
printf("%d\n",primes[i]);
}
}
void getPrimes(long numPrimes,long *primes)
{
long primeCount = 1;
long curPrime;
long curNum;
int isPrime;

primes[0] = 1;

curNum = 2;
while(primeCount < numPrimes)
{
isPrime = TRUE;
for(curPrime = 2;(curPrime < primeCount) && isPrime;curPrime++)
{
if((curNum % curPrime) == 0)
isPrime = FALSE;

}
if(isPrime)
{
primes[primeCount] = curNum;
primeCount++;
}
curNum++;
}
}
0

Commented:
Can't you just store them as strings and output them?

Or look at this site, it might have something. http://www.maths.uq.edu.au/~krm/N1.html

2     31
3     37
5     41
7     43
11    47
13    53
17    59
19    61
23    67
29    71

0

Commented:
i like the first method ;-)... it smacks of ingenuity...
0

Commented:
Sorry. Somehow with the copy the tabs got lost.
0

Commented:
You could probably optimize this  a little too by having curPrime only going upto curNum/2. Little less checking for the bigger numbers. i.e. if you are checking to see if 71 is a prime, you know you don't have to go above 35.
0

Commented:
1 is not prime.
0

Commented:
Isn't it? A prime is a number that isn't divisible by anything but 1 and itself. 1 would fit in that category. I don't have any other books besides my calculus book and they don't talk about primes there.
Either way, the code should still stay pretty much the same. Here is code to get rid of the 1 with a few minor mods to make it more efficient.

#include <stdio.h>
#define TRUE 1
#define FALSE 0
void getPrimes(long numPrimes, long *primes);

void main(void)
{
long primes[20];
long i;

getPrimes(20,primes);
for(i = 0;i<20;i++)
{
printf("%d\n",primes[i]);
}
}
void getPrimes(long numPrimes,long *primes)
{
long primeCount = 0;
long curPrime;
long curNum;
int isPrime;

curNum = 2;
while(primeCount < numPrimes)
{
isPrime = TRUE;
for(curPrime = 0;(curPrime < primeCount) && isPrime && (curNum/primes[curPrime] >= 2);curPrime++)
{
if((curNum % primes[curPrime]) == 0)
isPrime = FALSE;
}
if(isPrime)
{
primes[primeCount] = curNum;
primeCount++;
}
curNum++;
}
}

0

Commented:
jamesd78, you still there?
0