I wrote a C program which tells whether a given number is prime or not. But it has a problem in it. It is working fine for numbers other than multiples of 5. But it is showing the multiples of 5 as prime like 15, 25, 35, 45... . I am not able to find the error. I've tried comparing it with other programs on the internet but I am not able to find the error.
#include <stdio.h>
int primeornot(int a) {
int i;
for (i = 2; i <= a / 2; i++) {
if (a % i == 0) {
return 0;
break;
} else {
return 1;
}
}
}
main() {
int number_given_by_user;
printf("Enter a positive integer to find whether it is prime or not : ");
scanf("%d", &number_given_by_user);
if (primeornot(number_given_by_user)) {
printf("The given number is a prime number");
} else {
printf("The given number is not a prime number");
}
}
Not only multiples of 5 (for example, 9 is also considered prime by your code)
Your code is flawed. You are using a loop but only checking the first iteration, since you have a return
inside each branch of the condition inside your loop:
for(i=2;i<=a/2;i++)
{
if(a % i == 0)
{
return 0; // <------- (this one is fine, since finding a divisor means outright that this number isn't a prime)
break; // also, a break after a return is redundant
}
else
{
return 1; // <------- (however, this one is flawed)
}
}
In this form, your code only does return !(input % 2)
which is not a very good prime finding algorithm :-)
What you need to do is check all the iteration, and only if all of them go to the else
branch, the number is prime.
So, change to:
int primeornot(int a)
{
int i;
for(i=2;i<=a/2;i++)
{
if(a % i == 0)
{
return 0;
}
else
{
continue;
}
}
return 1; // loop has ended with no divisors --> prime!!
}
Or, better yet:
int primeornot(int a)
{
int i;
for(i=2;i<=a/2;i++)
{
if(a % i == 0)
{
return 0;
}
}
return 1; // loop has ended with no divisors --> prime!!
}