Skip to content

Commit f71c74a

Browse files
committed
Refactor Fibonacci calculation to handle large numbers
1 parent 5e42712 commit f71c74a

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

functions_nested_loops/104-fibonacci.c

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,30 +11,35 @@
1111
*/
1212
int main(void)
1313
{
14-
/* The first two Fibonacci numbers */
15-
unsigned long int a = 1, b = 2;
16-
17-
/* The next Fibonacci number */
18-
unsigned long int next;
19-
20-
/* The counter for the loop */
21-
unsigned long int count;
14+
/* The lower and upper parts of the current and next Fibonacci numbers */
15+
unsigned long int a1 = 0, a2 = 1, b1 = 0, b2 = 2, next1, next2, count;
2216

2317
/* Print the first two Fibonacci numbers */
24-
printf("%lu, %lu", a, b);
18+
printf("1, 2");
2519

2620
/* Calculate and print the next 96 Fibonacci numbers */
2721
for (count = 2; count < 98; count++)
2822
{
2923
/* Calculate the next Fibonacci number */
30-
next = a + b;
31-
32-
/* Update the current two Fibonacci numbers */
33-
a = b;
34-
b = next;
24+
next1 = a1 + b1;
25+
next2 = a2 + b2;
26+
if (next2 > 1000000000)
27+
{
28+
next2 -= 1000000000;
29+
next1++;
30+
}
3531

3632
/* Print the next Fibonacci number */
37-
printf(", %lu", next);
33+
if (next1 > 0)
34+
printf(", %lu%09lu", next1, next2);
35+
else
36+
printf(", %lu", next2);
37+
38+
/* Update current & next Fibonacci numbers for next loop iteration */
39+
a1 = b1;
40+
a2 = b2;
41+
b1 = next1;
42+
b2 = next2;
3843
}
3944

4045
/* Print a newline at the end */

0 commit comments

Comments
 (0)