-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathPrime_Numbers.cpp
More file actions
49 lines (40 loc) · 1.13 KB
/
Copy pathPrime_Numbers.cpp
File metadata and controls
49 lines (40 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
/*
- PRIME MUNBERS -
Example:
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
Is_Prime(21) --> will return 'false' value
Is_Prime(7) --> will return 'true' value
*/
// Boolean function that returns true if the input is Prime, else returns false
bool Is_Prime(int n) {
// If less than 2, or even number, and not 2 --> not prime
if (n < 2 || (n % 2 == 0 && n!=2))
return false;
// 2 is prime
if (n == 2)
return true;
/**
Iterate from 3 to half the user's entered number.
Once we are above half of the entered number (n) no
number divides evenly into n and it's therefore prime.
We start at 3 since we have already checked if n = 2.
We increment by 2 since we have already checked if the
number is even.
*/
for (int i = 3; i < (n / 2); i += 2)
if (n % i == 0)
return false;
return true;
}
int main() {
int n;
std::cout<<"Enter an integer greater than 1: ";
std::cin>>n;
Is_Prime(n);
if(Is_Prime(n)==true){
std::cout<<"True";
}else{
std::cout<<"False";
}
}