This is a short/simple program I wrote for a bigger project down the road.
Program Purpose: To store 125000 prime numbers in an long long type array.
If you examine my codes, you will notice that it is programmed to store the first 200 prime numbers, NOT 125000. Eventually, the program will have to store 125000 Prime Numbers. But for the time being and for testing/debugging purpose, I will use 200.
Standard Output line (cout) was included in this program to check to make sure the program is working as intended, but once this is converted to a class member function, that COUT line will go away.
I tried to run this program with 125000 index and it took OVER 5 minutes to get all 125000 prime numbers to standard output. I am afraid that it will take that much long to run the program once this program is converted to a class member function.
I am wondering if there is a way to improve the efficiency of this program before I use it for my project.
Algorithm I used in this program:
Starting with 2 (2 is the very first prime number), check to see if it is divisible by any number higher than 1 but lower than the number itself
For example, if number 2 is tested, it will simply be marked as a prime.
If number 3 is tested, the program will attempt to divide 3 by 2 and if it is not divisible, number 3 will be marked as a prime.
If number 10 is tested, the program will attempt to divide 10 by 2, 3, 4, 5, 6, 7, 8, 9 and if any of these can divide 10, then 10 will be marked as a non-prime.
Here is the Code.
Again, any assistance will be greatly appreciated.
Thank you all in advance!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
/************************************************************************
| Description: This program will identify the first 125000 Prime Numbers|
| and store them in an array |
************************************************************************/
#include <iostream>
int main ()
{
long long first125000Primes [200]; // Array to store the first 125000 Prime Numbers
int i = 0; // Used to control while loop
long long currentNumber = 2;
while ( i < 200 )
{
bool isPrime = true;
for ( int l = 2; l < currentNumber; l ++ )
{
if ( currentNumber % l == 0 )
{
isPrime = false;
}
}
if ( isPrime )
{
first125000Primes[i] = currentNumber;
std::cout << first125000Primes[i] << std::endl; // Send to standard output to verify that the array stores prime numbers
i ++; // Increment if the number is a prime
}
currentNumber ++;
}
return 0;
}
|