C++ Program to Check Prime Number
for (int i = 2; i * i <= n; i++) and returns prime if no divisor is found.Examples
How to Think About It
Algorithm
Code
#include <iostream> #include <cmath> int main() { int n; std::cout << "Enter a number: "; std::cin >> n; if (n < 2) { std::cout << n << " is not a prime number." << std::endl; return 0; } bool isPrime = true; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { isPrime = false; break; } } if (isPrime) std::cout << n << " is a prime number." << std::endl; else std::cout << n << " is not a prime number." << std::endl; return 0; }
Dry Run
Let's trace the input 7 through the code to see how it checks for prime.
Input number
User enters n = 7
Check if less than 2
7 is not less than 2, continue
Loop from 2 to sqrt(7)
Check i=2: 7 % 2 != 0, no divisor found
End loop
No divisors found, isPrime remains true
Print result
Print '7 is a prime number.'
| i | n % i | isPrime |
|---|---|---|
| 2 | 1 | true |
Why This Works
Step 1: Check small numbers
Numbers less than 2 are not prime by definition, so we handle them first.
Step 2: Loop to square root
We only check divisors up to the square root because any factor larger than that pairs with a smaller factor already checked.
Step 3: Determine primality
If no divisor divides the number evenly, the number is prime; otherwise, it is not.
Alternative Approaches
#include <iostream> int main() { int n; std::cout << "Enter a number: "; std::cin >> n; if (n < 2) { std::cout << n << " is not a prime number." << std::endl; return 0; } bool isPrime = true; for (int i = 2; i < n; i++) { if (n % i == 0) { isPrime = false; break; } } if (isPrime) std::cout << n << " is a prime number." << std::endl; else std::cout << n << " is not a prime number." << std::endl; return 0; }
#include <iostream> #include <cmath> bool isPrime(int n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } int main() { int n; std::cout << "Enter a number: "; std::cin >> n; if (isPrime(n)) std::cout << n << " is a prime number." << std::endl; else std::cout << n << " is not a prime number." << std::endl; return 0; }
Complexity: O(√n) time, O(1) space
Time Complexity
The loop runs up to the square root of n, so the time grows roughly with √n.
Space Complexity
Only a few variables are used, so space is constant.
Which Approach is Fastest?
Checking up to √n is faster than checking up to n-1, and using a function helps organize code but does not affect complexity.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check up to √n | O(√n) | O(1) | Efficient primality test |
| Check up to n-1 | O(n) | O(1) | Simple but slower |
| Function-based check | O(√n) | O(1) | Reusable and clean code |