|
An Introduction To Smalltalk Via "10000 factorial"
written by Peter William Lount version 1, 20041008 10:25am PDT Andy writes
"...until today I haven't come across a programming language which can even represent/work with anything this large "out of the box".
I'm sure there are other languages which can - I just haven't met them." - GimboLand.org.uk - Gibmoland #2 - Tiddly-Pom.com Then let us introduce you to Smalltalk, which has had out of the box large integers since at least Smalltalk-80 (i.e. 1980). Most Smalltalk versions support unlimited length integers and other numeric wonders such as Fractions. In a fraction like
3 / 4
the numerator and denomenator are remembered since the Fraction is an object like everything else in Smalltalk. Naturally Fraction object instances understand numerator and denomenator messages!
( 3 / 4 ) numerator
produces:
3
and
( 3 / 4 ) denominator
produces:
4
To find the factorial of a number simply type in the following into a Smalltalk workspace, select it and use the menu or keyboard command "print it" to execute the code and print it in the workspace (use "inspect it" or "explore it" to open an inspector or explorer window):
10000 factorial
which will produce a number with 35,660 digits which you can see here.
The Smalltalk source code for the Integer "factorial" method, which uses recursion, is:
factorial
"Answer the factorial of the receiver." self = 0 ifTrue: [^ 1]. self > 0 ifTrue: [^ self * (self - 1) factorial]. self error: 'Not valid for negative integers' You could have a fraction with a large denominator such as:
1 / (100 factorial)
which produces a fraction like so:
(1 / 933262154439441526816992388562667004907159682643816214685929
638952175999932299156089414639761565182862536979208272237582
51185210916864000000000000000000000000)
To convert it to a Float use:
(1 / (100 factorial)) asFloat
which will produce:
1.071510288125467e-158
in the familar limited precision Float representation.These examples were computed in Squeak Smalltalk. There are plenty of free online Smalltalk books available to learn Smalltalk from, and a number of freely available versions of Smalltalk for you to download and try out. Additional resources for learning Smalltalk are available. Check them out. Copyright 1 9 9 9 - 2 0 1 0 b y S m a l l t a l k . o r g "! , A l l R i g h t s R e s e r v e d . |
|