[This page is auto-generated; please prefer to read the article’s PDF Form.]
We will simply use the recurrence definition (1) of Fibonacci Numbers and sequentially calculate F3,F4,F5,…,Fn. Only the two latest calculated fibonacci numbers need to be remembered at any point, which will be added to obtain the next number of the sequence. Below is a portion of the C program for this. x and y remember the two latest fibonacci numbers.
We define the Predicate P as:
|
P is true just before we enter the loop, because F1 = F2 = 1. It remains true after each iteration of the loop — P is the loop-invariant. So, when the loop terminates and i has become equal to n, (i = n ∧ P) holds true. Further,
Thus, we would receive the value of Fn in y.
This algorithm requires n− 2 iterations, doing one addition of large numbers in each iteration. Thus it performs linear (in n) number of additions on large numbers. Though, such addition itself need not have constant time-complexity.
Copyright © 2020 Nitin Verma. All rights reserved.