Let’s start by writing a function to check for a prime number. We’ll iterate from 2 to the square root of the number, as a number greater than its square root won't be a divisor if no smaller number has been.
#include <stdio.h> #include <stdbool.h> #include <math.h> bool isPrime(int num) { if (num <= 1) return false; for (int i = 2; i <= sqrt(num); i++) { if (num % i == 0) return false; } return true; } int main() { int number; printf("Enter an integer: "); scanf("%d", &number); if (isPrime(number)) printf("%d is a prime number.", number); else printf("%d is not a prime number.", number); return 0; }
This code introduces the use of the sqrt()
function from the math library to optimize the prime checking process, reducing the number of iterations needed.