-
Sieve Of Erastothenes?
Im trying to determine prime numbers with this program, but the output i get is plain wrong.
Code:
#include <iostream>
bool checkprime(int n, int f);
int main()
{
bool numbers[122];
int i = 2, j = 2;
for(i = 2; i <= 120; i++)
{
numbers[i] = false; //Initiate the Bool array//
}
for(i = 2; i <= 120; i++)
{
for(j = 2; j <= 120; j++)
{
if(!numbers[i])
{
if(checkprime(i, j))
{
numbers[i] = true;
break;
}
}
}
}
for(i = 2; i <= 120; i++)
{
std::cout << i << " : " << numbers[i] << std::endl; //Print the Bool Array//
}
std::cin.get();
}
bool checkprime(int n, int f) //Function for checking primality//
{
if (n % f)
{
return(false);
}
else
{
return(true);
}
}
What am i doing wrong here?
-
Because of the way your for loops are set up, eventually, for every i, j will equal i, and calling checkprime(i, i) returns true. This is why you get lots of 1s. But I'm not familiar enough with the algorithm to explain how to fix this issue.
[edit] Hmm, it looks like you need to eliminate multiples. http://wwwhomes.uni-bielefeld.de/achim/prime_sieve.html
It seems like if you change the second for loop to
Code:
for(j = 2; j < i; j++)
you get the opposite output from what you are expecting -- 7 is 0 but 8 is 1, etc. (Unless maybe that was what you were expecting). This is empirically determined, however, and might be wrong. It makes sense, though, because it avoids the case I mentioned in the first part of this post. [/edit]
[edit=2] Yes, my fix works. It was just a small flaw in your logic. When you're checking for prime numbers, you want to check the numbers 2 <= x < N, not 2 <= x < infinity. Firstly, because x=N will always be true, as I've already identified, and secondly, because x>N will always be false. Or irrelevant anyway. [/edit]
-
Thanks alot Dwks, it's working now, but as you said it's not the output i expected, i'll try and fix that myself though :)