简体   繁体   中英

C Programming - Prime Number Check

I'm new to C programming and i'm wondering, why my code which job is to chceck if input number is prime. Here's the code:

#include <stdio.h>

bool prime(int);

int main()
{
    int x;
    x = getchar();
    if (x < 2)
        printf("its not prime\n");
    else
    {
        if (prime(x))
            printf("its prime\n");
        else
            printf("its not prime\n");
    }
    return 0;
}

bool prime(int x)
{
    for (int i = 2; i*i <= x; i++)
        if (x%i == 0)
        {
            return false;
            break;
        }
        else
            return true;
}

I don't know what i'm doing bad :/ Can you please help me? Thanks in advance! :)

Your code doesn't work because x=getchar() will accept only one character and let's you type 2 then the value of x will be 50 and 50 is not prime number, so you will get result not prime (but you are expecting ' prime ) the reason is when you type 2 it will assign it's ascii value to x because x is int and you are giving char .(And for bool to run you have to include stdbool.h in your code)

Right code for prime number checking is

#include <stdio.h>
#include <stdbool.h>
bool prime(int);

int main()
{
int x;
scanf("%d",&x);
if (x < 2)
    printf("its not prime\n");
else
{
    if (prime(x))
        printf("its prime\n");
    else
        printf("its not prime\n");
}
return 0;
}

bool prime(int x)
{
    int i;
    for (i = 2; i*i <= x; i++){
        if (x%i == 0)
            return false;
    }
    return true;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM