A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In C++, we can write a program to check whether a given number is prime or not.
The program to find if a given number is prime or not in C++ can be written in several ways. Here, we will discuss two different approaches to write this program.
Approach 1: Using a for loop
In this approach, we will use a for loop to check if the given number is divisible by any number between 2 and n/2. If the number is divisible by any number in this range, then it is not a prime number. Otherwise, it is a prime number.
Here is the code for the same:
#include <iostream> using namespace std; int main() { int n, i; bool isPrime = true; cout << "Enter a positive integer: "; cin >> n; for (i = 2; i <= n / 2; ++i) { if (n % i == 0) { isPrime = false; break; } } if (isPrime) cout << n << " is a prime number"; else cout << n << " is not a prime number"; return 0; }
Here, we have used a variable isPrime
to keep track of whether the number is prime or not. We have initialized it to true
at the beginning of the program. Then, we have used a for loop to iterate from 2 to n/2. Inside the loop, we have checked if the given number is divisible by the current number. If it is, then we have set isPrime
to false
and exited the loop using the break
statement.
After the loop, we have checked the value of isPrime
. If it is true
, then we have printed that the given number is a prime number. Otherwise, we have printed that it is not a prime number.
Approach 2: Using a while loop
In this approach, we will use a while loop to check if the given number is divisible by any number between 2 and n/2. If the number is divisible by any number in this range, then it is not a prime number. Otherwise, it is a prime number.
Here is the code for the same:
#include <iostream> using namespace std; int main() { int n, i = 2; bool isPrime = true; cout << "Enter a positive integer: "; cin >> n; while (i <= n / 2) { if (n % i == 0) { isPrime = false; break; } ++i; } if (isPrime) cout << n << " is a prime number"; else cout << n << " is not a prime number"; return 0; }
Here, we have initialized a variable i
to 2 and used a while loop to iterate while i
is less than or equal to n/2. Inside the loop, we have checked if the given number is divisible by the current number. If it is, then we have set isPrime
to false
and exited the loop using the break
statement.
After the loop, we have checked the value of isPrime
. If it is true
, then we have printed that the given number is a prime number. Otherwise, we have printed that it is not a prime number.
Comments
Post a Comment