File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Competitive Coding/Math/Primality Test/Optimized School Method Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ // A optimized school method based C++ program to check if a number is prime or not.
2+
3+ #include < bits/stdc++.h>
4+ using namespace std ;
5+
6+ bool isPrime (int n)
7+ {
8+ // Corner cases
9+ if (n <= 1 ) return false ;
10+ if (n <= 3 ) return true ;
11+
12+ // This is checked so that we can skip
13+ // middle five numbers in below loop
14+ if (n%2 == 0 || n%3 == 0 ) return false ;
15+
16+ for (int i=5 ; i*i<=n; i=i+6 )
17+ if (n%i == 0 || n%(i+2 ) == 0 )
18+ return false ;
19+
20+ return true ;
21+ }
22+
23+
24+ // Driver Program
25+ int main ()
26+ {
27+ isPrime (23 )? cout << " true\n " : cout << " false\n " ;// use of ternary operator
28+ isPrime (35 )? cout << " true\n " : cout << " false\n " ;
29+ return 0 ;
30+ }
31+
32+ Output:
33+
34+ true
35+ false
You can’t perform that action at this time.
0 commit comments