📌 Quick Answer
A prime number program in C checks whether a number has exactly two divisors (1 and itself). The logic divides the number by every integer from 2 up to its square root – if none divides evenly, it is prime.
Checking divisors only up to √n (instead of n) makes the program much faster for large numbers.
🔹 Key Takeaways
- A prime number is divisible only by 1 and itself (and must be > 1).
- Loop from 2 to n/2, or better, up to √n, testing for a zero remainder.
- If any divisor divides evenly, the number is not prime – stop early.
- Checking up to √n reduces the work dramatically for large numbers.
- The same logic in a loop prints all primes within a range.
Here’s an example program in C++ that checks whether a given number is prime or not:
#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i*i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int num;
cout << “Enter a number: “;
cin >> num;
if (isPrime(num)) {
cout << num << ” is a prime number.\n”;
} else {
cout << num << ” is not a prime number.\n”;
}
return 0;
}
In this program, the isPrime() function takes an integer n as its argument and returns true if it is a prime number, or false otherwise. The function uses a simple algorithm to check for primality: it tests whether n is divisible by any integer from 2 up to the square root of n. If n is divisible by any of these integers, then it is not a prime number.
In the main() function, the program prompts the user to enter a number, reads the input using cin, and then calls the isPrime() function to check whether the number is prime or not. The program then prints the result to the console using court.
Also, read An Introduction to Hypertext Markup Language (HTML): Benefits, Syntax, and Usage
Frequently Asked Questions
How do you check if a number is prime in C?
Test whether any integer from 2 up to the square root of the number divides it evenly; if none does (and the number is greater than 1), it is prime.
Why check divisors only up to the square root?
Because if a number n has a divisor larger than √n, it must also have a matching one smaller than √n – so checking up to √n finds all factors and is far faster.
Is 1 a prime number?
No. A prime number must have exactly two distinct positive divisors. 1 has only one divisor (itself), so it is not prime; the smallest prime is 2.
Related Topics on EngineeringHulk
- 👉 https://engineeringhulk.com/c-operators-all-7-types-with-detailed-explanations/
- 👉 https://engineeringhulk.com/what-is-c-programming-in-simple-words-a-comprehensive-guide/
