File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments