Link to home
Start Free TrialLog in
Avatar of jamesd78
jamesd78

asked on

primenumbers

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.
Avatar of deltree
deltree

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

i like the first method ;-)... it smacks of ingenuity...
ASKER CERTIFIED SOLUTION
Avatar of ggilman
ggilman

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry. Somehow with the copy the tabs got lost.
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.
Avatar of ozo
1 is not prime.
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++;
      }
}

jamesd78, you still there?