Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
1.1 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)
{
    float input;
    char waste;
    int number, flag, flag_prime = 0;

    printf("Enter a positive integer to check if it is a prime number: ");
    while((flag = scanf("%f", &input)) != 1 || input - (int)input != 0 || input <= 0){
        // conditions which are false include non-number input, negative integer and non-integer input

        if(flag == 0){
    /** for non-number input, scanf of number fails to load the input, an extra scanf
    of string is needed to remove the previous input **/
            scanf("%s", &waste);
        }
        printf("Your input is invalid. Please input a positive integer: ");
    }

    int output;
    number = (int)input;
    for(int i = 2; i <= sqrt(number); i++){
        output = number%i;
        if(output == 0){
            flag_prime = 1;
            break;
        }
    }

    if(flag_prime == 1){
        printf("The number %d is a prime number.\n", number);
    }
    else{
        printf("The number %d is not a prime number.\n", number);
    }

    return 0;
}