Saturday, 20 May 2017

C Program - Simple Prime Number Calculation

This can be optimised at least a bit - can you do this??

/* C Program to Calculate Prime Numbers
   A.D. Johnson, 10.95
   Used for speed comparison with a Interpreted Basic program.

    We determine Prime Numbers by taking the next number in a sequence
    then dividing it in turn by all the previous prime numbers we have
    so far calculated (each prime number is stored in an array as we go
    along). The process gets longer and longer every time we have a new
    prime number.
*/
#include <stdio.h>
#include <time.h>

#define MAX_PRIMES_FOUND 100000

/* Declare an array to store the Prime numbers we find.*/
long primes[MAX_PRIMES_FOUND];

/* Start of program. */
int main ()
{
   /* Set up the variables. */
   long no_primes = 0, divided;
   long number,j;
   time_t start_time;


   printf ("Prime Numbers Calculation Program. Calculating... ");

   /* Note start time. */
   start_time = time (NULL);

   /* Calculate Primes in the range 2 to 2500000 */
   for (number = 2; (number <= 2500000) && (no_primes < MAX_PRIMES_FOUND); number++)
   {
      /* Use this as a flag to show whether we have divided wholly. */
          divided = 1;

      /* Divide our current number by each of the primes we have found so far. */
          for (j = 0; (j < no_primes) ; j++)
          {
         /* The % is the "MOD" operation. */
                 divided = number % primes[j];

         /* If we had a whole division, break out of the loop. */
                 if (!divided)
                    break;
          }
      /* If we had a whole division, "divided" is 0 and hence
         prime number not found. */
          if (divided)
          {
         /* Store the prime number we found. */
                 primes[j] = number;
                 //printf ("%ld\n",j);

         /* Increase the number of primes found. */
                 no_primes++;
          }
   }

   /* Report. */
   printf ("\nFinished in %2.0f seconds!\n",difftime (time(NULL), start_time));
   printf ("Found %ld Prime numbers... Press a key to list them!\n", no_primes);

   /* Wait for a key to be pressed. */
   getchar();

   /* Show the prime numbers found. */
   for (j=0; j < no_primes; j++)
   {
      printf ("%8ld", primes[j]);
   }

   /* Wait for eenter to be pressed. */
   getchar();
   return 0;
}

No comments:

Post a Comment