Files
rose-ash/lib/smalltalk/tests/programs/fibonacci.st
giles 8daf33dc53
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Has been cancelled
smalltalk: fibonacci classic program + smalltalk-load + 13 tests
2026-04-25 05:35:24 +00:00

24 lines
593 B
Smalltalk

"Fibonacci — recursive and array-memoised. Classic-corpus program for
the Smalltalk-on-SX runtime."
Object subclass: #Fibonacci
instanceVariableNames: 'memo'!
!Fibonacci methodsFor: 'init'!
init memo := Array new: 100. ^ self! !
!Fibonacci methodsFor: 'compute'!
fib: n
n < 2 ifTrue: [^ n].
^ (self fib: n - 1) + (self fib: n - 2)!
memoFib: n
| cached |
cached := memo at: n + 1.
cached notNil ifTrue: [^ cached].
cached := n < 2
ifTrue: [n]
ifFalse: [(self memoFib: n - 1) + (self memoFib: n - 2)].
memo at: n + 1 put: cached.
^ cached! !