-
Notifications
You must be signed in to change notification settings - Fork 0
/
lastFib.js
105 lines (63 loc) · 2.08 KB
/
lastFib.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Just like in the "father" kata, you will have to return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers).
// You will just get much bigger numbers, so good luck bruteforcing your way through it ;)
function add(s1,s2){
let sum = "";
let s1Len = s1.length;
let s2Len = s2.length;
if(s2Len > s1Len ){
let temp = s2;
s2 = s1;
s1 = temp;
}
let carry = 0;
let a, b, temp, digitSum;
for (let i = 0; i < s1.length; i++) {
a = parseInt(s1.charAt(s1.length - 1 - i));
b = parseInt(s2.charAt(s2.length - 1 - i));
b = (b) ? b : 0;
temp = (carry + a + b).toString();
digitSum = temp.charAt(temp.length - 1);
carry = parseInt(temp.substr(0, temp.length - 1));
carry = (carry) ? carry : 0;
sum = (i === s1.length - 1) ? temp + sum : digitSum + sum;
}
return sum;
}
function lastFibDigit(n){
let current = 1, prev = 1, temp=0;
while (n > 2){
temp = current;
current = add(current.toString(), prev.toString());
prev = temp;
n--;
}
return parseInt(current.toString().slice(-1));
}
function lastFibDigit2(n){
let num = 60;
let lastDigitArray = [1,1];
let current = 1, prev = 1, temp=0;
while (num > 2){
temp = current;
current = current + prev;
prev = temp;
lastDigitArray.push(parseInt(current.toString().slice(-1)));
num--;
}
return lastDigitArray[n%60-1];
}
function lastFibDigit3(n){
let lastDigitArray = [1,1];
let current = 1, prev = 1, temp=0;
for (let i = 2; i < 60; i++){
temp = current;
current = current + prev;
prev = temp;
lastDigitArray.push(parseInt(current.toString().slice(-1)));
}
return lastDigitArray[n%60 === 0 ? 59 : n%60-1];
}
//21:6
//302:1
//4003:7
console.log(lastFibDigit3(21));