Reputation: 65
I'm trying to make a program that checks whether a given number is a prime number or not. However, my program just gives me the 2 time table, and I don't know why.
Here is my main class:
#include <stdio.h>
#include "defs.h"
#include "checkprime.c"
int Prime[MaxPrimes];
int main()
{
int UpperBound;
int N;
int *ba = &UpperBound;
printf("enter upper bound\n");
scanf("%d",ba);
Prime[2] = 1;
for (N = 3; N <= *ba; N+= 2)
{
CheckPrime(N);
if (Prime[N]== 1) printf("%d is a prime\n",N);
}
}
Here is my checkprime.c
#include "defs.h"
#include "externs.h"
int CheckPrime(int K)
{
int J;
J = 2;
while (1)
{
if (Prime[J] == 1)
{
if (K % J == 0)
{
Prime[K] = 0;
return 0;
}
J++;
}
break;
}
Prime[K] = 1;
}
Upvotes: 1
Views: 48
Reputation: 24052
There are some problems in CheckPrime
with the loop exit conditions. Use the following instead:
int CheckPrime(int K)
{
int J;
for (J=2; J*J <= K; J++) {
if (Prime[J] == 1) {
if (K % J == 0) {
Prime[K] = 0;
return 0;
}
}
}
Prime[K] = 1;
return 1;
}
The rest of it should work with this change.
Upvotes: 1