Fibonacci sequence

From Rosetta Code
Revision as of 18:22, 29 February 2008 by rosettacode>Mwn3d (Created task with Java)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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).

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>