Fibonacci sequence: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Python)
m (typo)
Line 55: Line 55:


=={{header|Python}}==
=={{header|Python}}==
===Iteractive===
===Iterative===
<python>def fibIter(n):
<python>def fibIter(n):
if n <= 2:
if n <= 2:

Revision as of 21:15, 29 February 2008

Task
Fibonacci sequence
You are encouraged to solve this task according to the task description, using any language you may know.

The Fibonacci sequence is a sequence of numbers defined as such:

Where n is an integer greater than 2:
F1 = F2 = 1
Fn = Fn-1 + Fn-2

Write a function to generate the nth Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).

BASIC

Works with: QuickBasic version 4.5

Iterative

<qbasic>FUNCTION itFib (n) IF (n <= 2) THEN

       itFib = 1

ELSE

       ans = 0
       n1 = 1
       n2 = 1
       n = n - 2
       DO WHILE (n > 0)
               ans = n1 + n2
               n1 = n2
               n2 = ans
               n = n - 1
       LOOP
       itFib = ans

END IF END FUNCTION</qbasic>

Recursive

<qbasic>FUNCTION recFib (n) IF (n <= 2) THEN

       recFib = 1

ELSE

       recFib = recFib(n - 1) + recFib(n - 2)

END IF END FUNCTION</qbasic>

Java

Iterative

<java>public static long itFibN(int n){ if(n <= 2)return 1; long ans = 0; long n1 = 1; long n2 = 1; for(n -= 2;n > 0;n--){ ans = n1 + n2; n1 = n2; n2 = ans; } return ans; }</java>

Recursive

<java>public static long recFibN(int n){ if(n <= 2) return 1; return recFibN(n-1) + recFibN(n-2); }</java>

Python

Iterative

<python>def fibIter(n):

   if n <= 2:
       return 1
   fibPrev = 1
   fib = 1
   for num in xrange(2, n):
       temp = fib
       fib += fibPrev
       fibPrev = temp
   return fib</python>

Recursive

<python>def fibRec(n):

   if n <= 2:
       return 1
   else:
       return fibRec(n-1) + fibRec(n-2)</python>