Search if number if prime or not in C
I was writing a C program to find out if a number is prime or not. Every time I run it and enter a number, the value of the input changes. PLease points to loopholes.
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
y=getchar();
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
I am using IDE Code :: Blocks with GCC compiler
source to share
getchar
returns the ASCII code of one character. Therefore, your program picks up the ASCII code of the first character of the number you entered and checks if it is simple.
Instead, you need to read an integer:
scanf("%d", &y);
Complete program:
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
scanf("%d", &y);
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else {
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
}
Note. You can stop whenx >= sqrt(y)
source to share
Well, you are calling getchar()
which is used to input one character, and this happens in your case:
-
getchar()
returns a character. - The character is then converted to an integer when you store it in a type variable
int
. - Hence, the integer contains the ASCII character of the input, i.e.
3
will be saved as51
, which is the reason for the input changes.
What you need to do is enter an integer instead of a character. Try the following:
scanf("%d", &y);
Hope it helps.
source to share
The first answers are correct regarding the input for y:
scanf("%d", &y);
Also note that you must loop to the square root of x, and no more, if you want to optimize your algorithm (I will not demonstrate here why this is a mathematical property).
#include <stdio.h>
#include <math.h>
// ...
int x;
int x_max;
int y;
scanf("%d", &y);
x_max = (int)floor(sqrt(y));
for(x=2;x<=x_max;++x){
// ...
source to share