- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Check Prime Number By Creating a Function
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.
Example
#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; }
Output
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 Articles
- Number prime test in JavaScript by creating a custom function?
- Python Program to Check Prime Number
- C++ Program to Check Whether a Number is Prime or Not
- C# Program to check if 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
- Haskell program to check whether the input number is a Prime number
- Python program to check if a number is Prime or not
- PHP program to check if a number is prime or not
- Java Program to Check Whether a Number is Prime or Not
- Check if a number is divisible by all prime divisors of another number in C++
- Bash program to check if the Number is a Prime or not
- Write a Golang program to check whether a given number is prime number or not
- Check if a number is Full Prime in C++
- C++ Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
