Implementation of isPrimeNumber(int) Function
To implement an isPrimeNumber(int) function in C that checks whether an integer is a prime number (a number greater than 1 that has no positive divisors other than 1 and itself), you can create a function that iterates through potential divisors. Here's an example of how to implement the isPrimeNumber()
function:
Example:
#include <stdio.h>
// Function to check if an integer is a prime number
int isPrimeNumber(int num) {
// Handle special cases
if (num <= 1) {
return 0; // 0 and 1 are not prime numbers
}
// Check for divisors from 2 to the square root of num
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // Found a divisor, not a prime number
}
}
return 1; // No divisors found, it's a prime number
}
int main() {
int number1 = 17; // Prime number
int number2 = 15; // Not a prime number
if (isPrimeNumber(number1)) {
printf("%d is a prime number.\n", number1);
} else {
printf("%d is not a prime number.\n", number1);
}
if (isPrimeNumber(number2)) {
printf("%d is a prime number.\n", number2);
} else {
printf("%d is not a prime number.\n", number2);
}
return 0;
}
In this example:
- The
isPrimeNumber()
function takes an integer num
as its parameter.
- It handles special cases: if
num
is less than or equal to 1, it returns 0
because 0 and 1 are not prime numbers.
- The function then checks for divisors of
num
by iterating from i = 2
up to the square root of num
. If it finds any divisor (i.e., num % i == 0
), it returns 0
because num
is not prime.
- If no divisors are found, the function returns
1
, indicating that num
is a prime number.
- In the
main()
function, two numbers (17 and 15) are checked using the isPrimeNumber()
function, and the result is printed.
Output:
17 is a prime number.
15 is not a prime number.
You can use this isPrimeNumber()
function to check whether any integer is a prime number by passing it as an argument to the function.