C++ Program to check Prime Number
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5,
Examples:
Input: n = 11 Output: true Input: n = 15 Output: false Input: n = 1 Output: false
// A school method based C++ program to check if a // number is prime #include <bits/stdc++.h> using namespace std; bool isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Driver Program to test above function int main() { isPrime(11) ? cout << " true\n" : cout << " false\n"; isPrime(15) ? cout << " true\n" : cout << " false\n"; return 0; } |
chevron_right
filter_none
Output:
true false
Time complexity of this solution is O(n)
Optimized School Method
// A optimized school method based C++ program to check // if a number is prime #include <bits/stdc++.h> using namespace std; bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Driver Program to test above function int main() { isPrime(11) ? cout << " true\n" : cout << " false\n"; isPrime(15) ? cout << " true\n" : cout << " false\n"; return 0; } |
chevron_right
filter_none
Output:
true false
Please refer complete article on Primality Test | Set 1 (Introduction and School Method) for more details!
Recommended Posts:
- Create Directory or Folder with C/C++ Program
- C Program to Swap two Numbers
- C Program for Bubble Sort on Linked List
- C program to invert (making negative) an image content in PGM format
- C Program for Selection Sort
- C Program for Bubble Sort
- C Program for Insertion Sort
- C Program for Radix Sort
- C/C++ Program for n-th Fibonacci number
- C Program for Counting Sort
- C Program for Binary Search (Recursive and Iterative)
- C Program for Min Cost Path
- C/C++ Program for Longest Increasing Subsequence
- C Program for Pancake sorting
- C Program for Binary Insertion Sort



