-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprojectEuler003.cpp
More file actions
62 lines (49 loc) · 1.26 KB
/
Copy pathprojectEuler003.cpp
File metadata and controls
62 lines (49 loc) · 1.26 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
50
51
52
53
54
55
56
57
58
59
60
61
62
/* Problem 3
Largest Prime Factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
*/
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime (int x) {
bool prime = true;
double x_d = static_cast<double> (x);
int upperLimit = static_cast<int> (sqrt (x));
if (upperLimit % 2 == 0) {
upperLimit++;
}
for (int divisor = 3; divisor <= upperLimit; divisor++) {
if (x % divisor == 0) {
prime = false;
break;
}
}
return prime;
}
void main () {
// double num = 13195;
double num = 600851475143;
bool primeFactorFound = false;
// double num_d = static_cast<double> (num);
int largestCandidate = static_cast<int> (sqrt (num));
cout << num << endl;
cout << largestCandidate << endl;
if (largestCandidate % 2 == 0) {
largestCandidate++;
}
while (!primeFactorFound && largestCandidate > 0) {
bool primeFound = isPrime (largestCandidate);
if (!primeFound) {
largestCandidate -= 2;
} else {
double otherFactor = num / (double)largestCandidate;
if (floor (otherFactor) == otherFactor) {
primeFactorFound = true;
break;
}
largestCandidate -= 2;
}
}
cout << largestCandidate << endl;
}