Print If Prime or Not
In this final step, we will enhance our prime number checking program by adding more detailed output and allowing multiple number checks.
Let's modify the program to provide more comprehensive output:
nano ~/project/prime_checker.c
Update the code with an improved interface:
#include <stdio.h>
#include <math.h>
int is_prime(int number) {
// Numbers less than 2 are not prime
if (number < 2) {
return 0;
}
// Check divisibility from 2 to square root of number
for (int i = 2; i <= sqrt(number); i++) {
if (number % i == 0) {
return 0; // Not prime if divisible
}
}
return 1; // Prime if no divisors found
}
void print_prime_details(int number) {
if (is_prime(number)) {
printf("%d is a PRIME number!\n", number);
printf("Explanation:\n");
printf("- It is only divisible by 1 and itself\n");
printf("- No other divisors were found between 2 and √%d\n", number);
} else {
printf("%d is NOT a prime number.\n", number);
// Find and print the smallest divisor
for (int i = 2; i <= sqrt(number); i++) {
if (number % i == 0) {
printf("Explanation:\n");
printf("- Divisible by %d\n", i);
printf("- %d × %d = %d\n", i, number/i, number);
break;
}
}
}
}
int main() {
int number, continue_check;
do {
printf("Enter a positive integer to check if it's prime: ");
scanf("%d", &number);
print_prime_details(number);
printf("\nDo you want to check another number? (1=Yes, 0=No): ");
scanf("%d", &continue_check);
} while (continue_check == 1);
printf("Thank you for using the Prime Number Checker!\n");
return 0;
}
Compile the program:
gcc ~/project/prime_checker.c -o ~/project/prime_checker -lm
Example outputs:
Enter a positive integer to check if it's prime: 17
17 is a PRIME number!
Explanation:
- It is only divisible by 1 and itself
- No other divisors were found between 2 and √17
Do you want to check another number? (1=Yes, 0=No): 1
Enter a positive integer to check if it's prime: 20
20 is NOT a prime number.
Explanation:
- Divisible by 2
- 2 × 10 = 20
Do you want to check another number? (1=Yes, 0=No): 0
Thank you for using the Prime Number Checker!
Key improvements:
- Added detailed explanations for prime and non-prime numbers
- Implemented a loop to allow multiple number checks
- Provides more educational output about number properties