- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

A prime number is a whole number that is greater than one and the only factors of a prime number should be one and itself.

Some of the first prime numbers are −

2, 3, 5, 7, 11, 13 ,17

A program to check if a number is prime or not using a function is as follows.

#include <iostream> using namespace std; void isPrime(int n) { int i, flag = 0; for(i=2; i<=n/2; ++i) { if(n%i==0) { flag=1; break; } } if (flag==0) cout<<n<<" is a prime number"<<endl; else cout<<n<<" is not a prime number"<<endl; } int main() { isPrime(17); isPrime(20); return 0; }

17 is a prime number 20 is not a prime number

The function isPrime() is used to find out if a number is prime or not. There is a loop that runs from 2 to half of n, where n is the number to be determined. Each of the values of the loop divide n. If the remainder of this division is 0, that means n is divisible by a number, not one or itself. So, it is not a prime number and the flag is set to 1. Then break statement is used to exit the loop as shown below −

for(i=2; i<=n/2; ++i) { if(n%i==0) { flag=1; break; } }

If the value of flag remained zero, then the number is a prime number and that is displayed. If the value of flag was changed to one, then the number is not a prime number and that is displayed.

if (flag==0) cout<<n<<" is a prime number"; else cout<<n<<" is not a prime number";

The function isPrime() is called from the main() function for the values 17 and 20. This is shown as follows.

isPrime(17); isPrime(20);

- Related Questions & Answers
- Number prime test in JavaScript by creating a custom function?
- Python Program to Check Prime Number
- C# Program to check if a number is prime or not
- C++ Program to Check Whether a Number is Prime or Not
- C Program to Check Whether a Number is Prime or not?
- Write a C# program to check if a number is prime or not
- Check if a number is divisible by all prime divisors of another number in C++
- Python program to check if a number is Prime or not
- PHP program to check if a number is prime or not
- Check if a number is Full Prime in C++
- Write a Golang program to check whether a given number is prime number or not
- Bash program to check if the Number is a Prime or not
- Java program to print a prime number
- Write a C# program to check if a number is divisible by 2
- C++ Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers

Advertisements