I'ma beginner in C and I have to convert The Sieve of Eratosthenes algorithm into C code. This is the algorithm given: *START Initialize the array is_prime so that all the values of the elements will be TRUE. set the value of is_prime[1] to be FALSE (since 1 is NOT prime.) For I=2 until sqrt(N) execute: set all the multiples of I to FALSE, starting with I*I until N. Print all the indexes of is_prime that hold the value TRUE. END*
Here is my code so far:
#include <stdio.h>
#include <math.h>
#define N 300
void displayPrime (bool checkPrime);
bool checkPrime (int num);
main()
{
bool is_prime[N+1];
displayPrime(is_prime);
getchar();
}
void displayPrime (bool check)
{
int I;
for(I=1; I<N; I++)
{
checkPrime(is_prime[I]);
if(is_prime[I]==TRUE)
{
printf("%d\n", I);
}
else if(is_prime[I]==FALSE)
{
printf("");
}
}
}
bool checkPrime (int num)
{
int num;
is_prime[1]=FALSE;
for(I=2; I<=sqrt(N); I++)
{
for(num=I; num<=N/num; num=num*I)
{
is_prime[num]=FALSE;
}
return(is_prime[I]);
}
}
The program does not compile, and I'm wondering what is wrong with the program. Thank you
I am not looking into the algorithm. This is the working code (Using visual studio):
#include <stdio.h>
#include <math.h>
#define N 300
void displayPrime (bool checkPrime);
bool checkPrime (int num);
bool is_prime[N+1];
void displayPrime (bool check)
{
int I;
for(I=1; I<N; I++)
{
checkPrime(is_prime[I]);
if(is_prime[I]==true)
{
printf("%d\n", I);
}
else if(is_prime[I]==false)
{
printf("");
}
}
}
bool checkPrime (int num)
{
int I;
is_prime[1]=false;
for(I=2; I*I<=N; I++)
{
for(num=I; num<=N/num; num=num*I)
{
is_prime[num]=false;
}
return(is_prime[I]);
}
}
void main()
{
displayPrime(is_prime);
getchar();
}
I have changed these things:
{}
TRUE
should be true
and FALSE
should be false
.Anyway Sieve
has a lot of good implementation. Try them out.