// A Fibonacci sequence starts with two 1s. Each subsequent number // is the sume of the two numbers that came before: 1, 1, 2, 3, 5, // 8, 13, 21, and so on. Write a program to find the nth Fibonacci // number: fib(1) is 1, and fib(4) is 3. As a bonus, solve the // problem with recursion and with loops. // Define the FIB method in the global (Lobby) name space. fib := method( nth, // First, check to see if we are dealing with base values; that // is, values 1th and 2th that are not base on previous sums. if( ((nth == 1) or (nth == 2)), return( 1 ); ); // If we have made it this far, then we are dealing with values // that we need to calculate. We shall loop up to the nth value, // building an aggregate sum. // Start out with the known base values. nthSub2 := 1; nthSub1 := 1; // As we iterate up to our target nth, we're going to need an // intermediary value to keep track of the current sum before // we shift the "view" to (nth-1) and (nth-2). nthSub0 := (nthSub1 + nthSub2); // Loop up to the nth position within the sequence. Since we // already know the values at position 1 and 2, we are going // to start this iteration at 3. for( i, 3, nth, 1, // Get the sum at this position. nthSub0 = (nthSub1 + nthSub2); // Shift (nth-1) and (nth-2) values down for the next // iteration. // // NOTE: These values are now only relevant on the (ith+1) // loop. They are no longer meaningful for the ith loop. nthSub2 = nthSub1; nthSub1 = nthSub0; ); // Return the last computed sum in the sequence. return( nthSub0 ); ); // ---------------------------------------------------------- // // ---------------------------------------------------------- // // Test the first 10 values of the Fibonacci sequence. fib( 1 ) println(); fib( 2 ) println(); fib( 3 ) println(); fib( 4 ) println(); fib( 5 ) println(); fib( 6 ) println(); fib( 7 ) println(); fib( 8 ) println(); fib( 9 ) println(); fib( 10 ) println();