Mukul Mehta
Mukul Mehta

Reputation: 39

Finding if a Number if Prime or not In C

I was writing a C Program to find if a number is prime or not. Everytime I run it and enter a number, the value of the input changes. PLease point out the 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 use the Code::Blocks IDE with GCC Compiler

Upvotes: 3

Views: 207

Answers (4)

Itban Saeed
Itban Saeed

Reputation: 1666

Well, you are calling getchar() which is used to input a single character and this is what happens in your case:

  • getchar() returns a character.
  • Character is then converted into integer when you store it in variable of type int.
  • Hence that integer contains the ASCII of input character i.e. 3 will be stored as 51 that is the reason input changes.

What you need to do is to input an integer instead of character. Try this:

scanf("%d", &y);

Hope this helps.

Upvotes: 2

Tarik
Tarik

Reputation: 11209

getchar returns the ASCII code of a single character. Consequently, your program picks up the ASCII code of the first character of the number you input and checks if it is prime.

Instead, you need to read an integer:

scanf("%d", &y);

The 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 when x >= sqrt(y)

Upvotes: 5

Yu Hao
Yu Hao

Reputation: 122383

As the name implies, getchar() gets a single character from standard input. For example, if you enter 3, the y gets the ASCII code of the character '3', which is obviously not what you want.

Try scanf:

scanf("%d", &y);

Upvotes: 5

John
John

Reputation: 61

First answers are correct about input for y:

scanf("%d", &y);

Also, please note that you should loop until square root of x, and not more if your want to optimize your algorithm (I won't demonstrate here why, it's 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){

// ...

Upvotes: 1

Related Questions