Introduction
In this lab, you will learn how to write a C++ program to check whether a given number is a prime number or not. A prime number is a number that is only divisible by 1 and itself. It is an important concept in number theory and has many important applications in cryptography.
Create a new C++ source file
First, create a new C++ source file named main.cpp in ~/project/ directory.
cd ~/project
touch main.cpp
Write the C++ program to check prime number
Copy the following code into the main.cpp file:
#include <iostream>
using namespace std;
int main() {
int n, i;
bool isPrime = true;
// Get the number from the user
cout << "Enter a positive integer: ";
cin >> n;
// Check whether the number is prime
for(i=2; i<=n/2; i++) {
if(n%i == 0) {
isPrime = false;
break;
}
}
if(isPrime) {
cout << n << " is a prime number." << endl;
} else {
cout << n << " is not a prime number." << endl;
}
return 0;
}
This program takes an integer n from the user and checks whether it is prime or not. If it's prime, print n is a prime number.; otherwise, print n is not a prime number.
Compile and Run the Program
Open the terminal in Ubuntu system and navigate to the ~/project/ directory:
cd ~/project
Compile the main.cpp code by running the following command:
g++ main.cpp -o main
Run the compiled executable file by executing the following command:
./main
Test the Program
Now, enter different numbers to check whether they are prime or not:
Enter a positive integer: 17
17 is a prime number.
Enter a positive integer: 57
57 is not a prime number.
Summary
In this lab, you learned how to write a C++ program to check whether a given number is a prime number or not. You now have a solid understanding of this concept, which is important in number theory and cryptography.



