Fibonacci numbers (Smalltalk)

From LiteratePrograms

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

Recursion

This simple method uses recursion to return Fibonacci number at receiver position.

fibonacciRecursive
	"calculates Fibonacci number at position number self recursively"
	| num1 num2 res |
	self<0 ifTrue: [self error: 'Not able to calculate Fibonacci number at negative position'].
	self<2 ifTrue: [^1].
	num1 := (self - 1) fibonacciRecursive.
	num2 := (self - 2) fibonacciRecursive.
	res := num1 + num2.
	^res


Iteration

Iterative implementation gives Fibonacci number at receiver position.

fibonacci
	"calculates Fibonacci number at position number self"
	| num1 num2 res |
	self<0 ifTrue: [self error: 'Not able to calculate Fibonacci number at negative position'].
	self<2 ifTrue: [^1].
	num1 := 1.
	num2 := 1.
	self-1 timesRepeat: [res := num1 + num2.
			num2 := num1.
			num1 := res].
	^res
Download code
Views