Skip to content

Commit 1071da1

Browse files
Merge pull request #77 from venkat-abhi/add-last-fib
add calculator for last digit of nth fibonacci number
2 parents 8263727 + d29d92c commit 1071da1

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

last-digit-fibonacci.c

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#include <stdlib.h>
2+
#include <stdio.h>
3+
4+
int last_digit_fib_optimized(const int index)
5+
{
6+
int first = 0;
7+
int second = 1;
8+
int current = 0;
9+
10+
for (int i = 2; i <= index; ++i) {
11+
current = (first + second) % 10;
12+
first = second;
13+
second = current;
14+
}
15+
16+
return (current);
17+
}
18+
19+
/* This is the direct solution for reference */
20+
int last_digit_fib_naive(const int index)
21+
{
22+
int *arr;
23+
arr = (int *)malloc((index+1) * sizeof(int));
24+
arr[0] = 0;
25+
arr[1] = 1;
26+
27+
for (int i = 2; i <= index; ++i) { // store only the last digit of each index
28+
arr[i] = (arr[i - 1] + arr[i - 2]) % 10;
29+
}
30+
31+
int res = arr[index];
32+
return (res);
33+
}
34+
35+
int main(int argc, char **argv)
36+
{
37+
int index = 0;
38+
scanf("%d", &index);
39+
40+
printf("%d\n", last_digit_fib_optimized(index));
41+
42+
return 0;
43+
}

0 commit comments

Comments
 (0)