Complementary task for topic: 4

M Nemeth · 2023-08-29 15:21:04.617219'

Functions: Prime Check

Functions: Prime Check

Write a C function is_prime that takes an integer as input and returns 1 if the number is prime (only divisible by 1 and itself), and 0 otherwise.

Hint:

Solution
#include 

// Function to check if a number is prime
int is_prime(int num) {
    if (num <= 1)
        return 0;

    for (int i = 2; i * i <= num; ++i) {
        if (num % i == 0)
            return 0;
    }
    return 1;
}

int main() {
    int num;
    printf("Enter a number to check if it is prime: ");
    scanf("%d", &num);

    if (is_prime(num))
        printf("%d is a prime number.\n", num);
    else
        printf("%d is not a prime number.\n", num);

    return 0;
}



Explanation
The is_prime function checks if a given number is prime by iterating from 2 to the square root of the number and checking if the number is divisible by any smaller integer. If it is, the number is not prime. Otherwise, it is prime. The main function takes a number as input, calls the is_prime function, and prints the result.
< < previous    next > >