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

+3


source to share


4 answers


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)

+5


source


As the name suggests, getchar()

gets one character from standard input. For example, if you enter 3, y

you get an ASCII character code '3'

, which is clearly not the one you want.

Try scanf

:



scanf("%d", &y);

      

+5


source


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 as 51

    , 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.

+2


source


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){

// ...

      

+1


source







All Articles