#include <stdio.h>
#include <stdlib.h>
//this function checks if the given number prime or not
int prime_check(int number) {
for (int i = 2; i < number; i ) {
if (number % i == 0) {
return 1;
} else if (number == 2) {
return 0;
} else {
return 0;
}
}
}
//the problem is that when i entered the integer 2 i got that "the number is not prime" output
int main() {
int user_n;
printf("pls enter the number \n");
scanf("%d", & user_n);
if (prime_check(user_n) == 0) {
printf("the number is prime \n");
} else {
printf("its not prime.. \n");
}
}
CodePudding user response:
If the selected number is 2, the for
loop is never entered because i < number
is initially false. The function then reaches the end without returning a value.
If a function is declared to return a value but does not, and the calling function attempts to use the return value, this triggers undefined behavior in your program, which basically means that no particular result is guaranteed.
Related to this, you have a logic error. The body of the for
loop has a return
statement in every path so no more that one iteration of the loop will occur. This causes all odd numbers to be reported as prime.
You only need to perform the %
check inside of the loop. If that condition is not met, then continue on with the loop. If the loop exits, then you know you have a prime number and can return 0.
int prime_check(int number)
{
for (int i = 2;i<number;i ){
if (number % i == 0){
return 1;
}
}
return 0;
}
Also, you can reduce the number of loop iterations by changing the condition to i<=number/i
(which is mathematically the same as i*i<=number
but avoids overflow), since you don't need to check values greater than the square root of the number in question.
CodePudding user response:
You have an explicit if condition that check if parameter == 2 at the first iteration (look at the comment below)
for (int i = 2;i<number;i ){
//here
if (number % i == 0 ){
return 1 ;
}
else if (number == 2){
return 0;
}
else {
return 0 ;
}
}
CodePudding user response:
You can't enter to for loop only if the condition i < number
is TRUE
SO you should check if number = 2 and number < 2 before your for loop
The new version of your code:
#include <stdio.h>
#include <stdlib.h>
int prime_check(int number) {
if (number == 2) {
return 0;
} else if (number < 2) {
return 1;
} else {
for (int i = 2; i < number; i ) {
if (number % i == 0) {
return 1;
} else if (number == 2) {
return 0;
} else {
return 0;
}
}
}
}
int main() {
int user_n;
printf("pls enter the number \n");
scanf("%d", & user_n);
if (prime_check(user_n) == 0) {
printf("the number is prime \n");
} else {
printf("its not prime.. \n");
}
}