C Prime Number Program
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This means that a prime number can only be divided evenly by 1 and the number itself without leaving a remainder.
Logic to Check for Prime Numbers:
- Input a number from the user.
- Check if is less than or equal to 1. If so, it is not prime.
- For numbers greater than 1, check for factors from 2 up to the square root of . If is divisible by any of these numbers, it is not prime.
- If no divisors are found, is prime.
Program:
Here’s a simple C program to check if a number is prime:
Explanation:
Variables:
int n
: Holds the integer input by the user.int i
: Loop variable for checking divisors.int isPrime
: A flag initialized to 1 (true), assuming the number is prime.
Input:
- The user is prompted to enter a positive integer.
Invalid Input Check:
- If is less than or equal to 1, the program states that it is not a prime number and exits.
Loop for Checking Factors:
- The program loops from 2 to the square root of (inclusive) to check for divisors.
- If is divisible by any ,
isPrime
is set to 0 (false), and the loop breaks.
Output:
- After checking, the program prints whether is a prime number or not based on the value of
isPrime
.
- After checking, the program prints whether is a prime number or not based on the value of
Sample Output:
Example 1:
Example 2:
Key Points:
- Efficiency: The program only checks divisibility up to the square root of , which significantly reduces the number of iterations for larger numbers compared to checking up to .
- Input Validation: The program checks for numbers less than or equal to 1 to avoid unnecessary calculations.
- Output Clarity: Clear messaging is provided to the user based on whether the number is prime or not.