Answer to Question #308230 in C for ahmed

Question #308230

Write a program that reads a positive integer and checks if it is a prime.


1
Expert's answer
2022-03-15T02:57:27-0400
#include <stdio.h>

int is_prime(int n) {
    int i;


    if (n < 2) {
        return 0;
    }
    if (n == 2) {
        return 1;
    }

    i = 3;
    while (i*i <= n) {
        if (n%i == 0) {
            return 0;
        }
        i += 2;
    }
    return 1;
}

int main() {
    int n;

    printf("Enter a positive number: ");
    scanf("%d", &n);

    if (is_prime(n)) {
        printf("The number is prime\n");
    }
    else {
        printf("The number is not prime\n");
    }

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS