Fibonacci numbers (Icon)

From LiteratePrograms
Jump to: navigation, search
Other implementations: bc | C | C Plus Plus templates | dc | E | Erlang | FORTRAN | Haskell | Icon | Java | JavaScript | Lisp | Logo | Lua | Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Prolog | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | Smalltalk | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by


 F(n) =
 \begin{cases}
   0             & n = 0 \\
   1             & n = 1 \\
   F(n-1)+F(n-2) & n > 1 \\
  \end{cases} .

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.


In this article we show two ways of calculating fibonacci numbers in Icon.

<<fib.i>>=

fib

fastfib

test

[edit] Recursive

This is a very simple recursive implementation. This will become slow on big numbers, because the numbers are recalculated for each recursion.

<<fib>>=
procedure fib(n)
	if n<2 then return n
	else return fib(n-1)+fib(n-2)
end



[edit] Iterative

This is a faster, but also somewhat more complicated way to calculate fibonacci numbers. To avoid recalculation and recursion, we store the two previous numbers in local variables.

<<fastfib>>=
procedure fastfib(n)
	local prevfib, currfib, nfib
	nfib:=2
	prevfib:=1
	currfib:=1
	while nfib<n do {
		prevfib:=:currfib
		currfib+:=prevfib
		nfib+:=1
	}
	return currfib
end

[edit] Test

If we run this test code, we can see that the iterative method is significantly faster then the recursive.

<<test>>=
procedure main()
	local n

	n:=1
	while n<30 do {
		write(fib(n))
		n+:=1 
	}

	n:=1
	while n<30 do {
		write(fastfib(n))
		n+:=1 
	}
end
Download code
hijacker
hijacker
hijacker
hijacker