Reputation:
I have created this C program that is supposed to tell me how many prime numbers are between 1-25, but it is printing that every number is prime number. Please Help
#include<stdio.h>
int main(void) {
int n = 1, counter = 0;
int i, flag = 0;
while ( n <= 25 )
{
for ( i = 2; i <= (n/2); i++ )
{
if (n%i == 0)
{
flag = 0;
}
}
if (flag == 0)
{
counter++;
printf("%d is Prime Number.\n", n);
}
else
{
printf("%d is not Prime Number.\n", n);
}
n++;
}
return 0;
}
Upvotes: 0
Views: 126
Reputation: 3045
flag = 0;
Your flag is always 0
. You have to set it to 1
, while entering the while
loop
while ( n <= 25 ) {
flag = 1; //<-- here
for ( i = 2; i <= (n/2); i++ ) {
You can as well break
in the segment, just for efficiency
if (n%i == 0)
{
flag = 0;
break;
}
Upvotes: 6
Reputation: 3162
you can use the code as,
for ( i = 2; i <= sqrt(n); i++ )
{
if (n%i == 0)
{
flag = 0;
}
}
if (flag == 0)
{
counter++;
printf("%d is Prime Number.\n", n);
flag=1;
}
else
{
printf("%d is not Prime Number.\n", n);
}
n++;
use sqrt()
instead of n/2
program will be more efficient.
Upvotes: 0