-
Notifications
You must be signed in to change notification settings - Fork 0
/
FibonacciDiv2.hpp
31 lines (30 loc) · 942 Bytes
/
FibonacciDiv2.hpp
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
#include <iostream>
using namespace std;
class FibonacciDiv2
{
public:
int find(int N) {
int res = 0;
int fibLeft = 0;
int fibRight = 1;
int nextFib = fibLeft + fibRight;
// Find fibonacci values before and after N
while (nextFib < N) {
nextFib = fibLeft + fibRight;
fibLeft = fibRight;
fibRight = nextFib;
}
// cout << "Left " << fibLeft << " Right " << fibRight << " next " << nextFib << endl;
// Calculate the differences between N and the fibonacci values before and after
int leftDiff = N - fibLeft;
int rightDiff = fibRight - N;
// cout << "left diff " << leftDiff << " right diff " << rightDiff << endl;
// Choose the smallest difference
if (leftDiff < rightDiff) {
res = leftDiff;
} else {
res = rightDiff;
}
return res;
}
};