Reputation: 9
I know this may be a dumb question, but I cannot find what is wrong with this code. Here I have initialized a function which checks whether the number entered is prime or not.
#include <stdio.h>
int check_prime(int n)
{
int i,count=0;
for(i=2;i<n/2;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==0)
{
printf("the number is prime");
}
}
int main()
{
int n;
printf("enter the number,\n");
scanf("%d",&n);
int check_prime(int n);
return 0;
}
the output only shows:
enter the number
after I enter the number it does not display anything.
Upvotes: 0
Views: 164
Reputation: 153447
after I enter the number it does not display anything
Aside from the non-call to check_prime()
should be replaced with a call
// int check_prime(int n); // This is only a function declaration.
check_prime(n);
Prime detection is very slow for large values and can be significantly sped up.
//for(i=2;i<n/2;i++) {
// if(n%i==0) {
// count++;
// }
//}
// vvvv
for(i=2; i<=n/i; i++) {
if(n%i==0) {
count++;
break; // add
}
}
Upvotes: 0
Reputation: 2398
There appears to be 3 problems.
The return type of check_prime
You declare int check_prime(int n)
, which means the function should return an int
. In this case, your function never returns anything, it just prints stuff, so a return type of void
is more suitable.
You declare check_prime
again in main
instead of calling it
In main
, when you say int check_prime(int n);
you are actually declaring a check_prime
function again, not calling it. You would call it as check_prime(n);
.
The algorithm has a bug in it
As it is, your algorithm thinks 4
is a prime number (which it is not).
In your for
loop, you check if n
is divisible by the integers from 2
to (n / 2) - 1
, because the termination condition is i < n/2
, which is true when i == n / 2
. For the example of 4
, this mean it never runs the for
loop.
The termination condition in the loop should be changed to i <= n / 2
, as in:
for(i = 2; i <= n / 2; i++)
Upvotes: 1
Reputation: 450
The answer above is perfect. Since you said you are new to the programming world, I'd love to explain a bit more.
int check_prime(int n);
is how you declare a function.check_prime(n); //n is an integer
is how you call the function.Upvotes: 2
Reputation: 75062
int check_prime(int n);
Is not a call of function but a declaration of function.
It should be
check_prime(n);
to call the function.
Upvotes: 3