Can anyone give me some tips on how to print prime numbers from 2 to 100,000? I know I should be using a for loop but I'm unsure of how to really go about this. Also, is there a way to output the number of prime numbers that were displayed? Thanks in advance for any advice!
I actually found some answers online and I've come up with this. It works. But I guess, more than anything, I'd like an explanation of what is going on in the code. This works, but it doesn't help me much if I don't get what's happening. Also, I still need help figuring out how to print the number of primes that were printed.
//Lists prime numbers under 100,000:
int p;
for (int i=2; i<100000; i++)
{
if (p<i)
{
p=i;
}
bool prime=true;
for (int x=2; x*x<=i; x++)
{
if (i % x == 0)
{
prime=false;
break;
}
}
if(prime) cout << i << " ";
}
cout << p << endl;
I don't quite understand what's happening from lines 9 to 20. What is the second for loop's purpose and how does it work with the first for loop? I know that the first for loop is printing numbers from 2 to 100,000. Is the second for loop calculating the primes? Also, I don't get what is happening in line 12. What does "%" do?
bool prime=true; //flag
for (int x=2; x*x<=i; x++)// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes -->this will explain the loop
{
if (i % x == 0)//mod function (it just gives remainder) --> for eg 5/3 will give a remainder 2
{
prime=false;//flag turned false
break;//out of loop
}
}
if(prime) cout << i << " ";
}
cout << p << endl;//printing the prime
// Generates a list of all +ve numbers < limit, prime = 0, non-prime = 1
int* primeList( constint aLimit)
{
int* sieve = newint[aLimit];
for ( int i = 2; i <= sqrt(aLimit); i++)
for (int j = i * i; j < aLimit; j += i)
sieve[j] = 1;
sieve[aLimit] = -1; // terminator
return sieve;
}
This function is a small embellishment on the previous one by creating an array of integers up to a selected limit and sieving primes and non-primes as the comment. Create the array and read and count as you want.