Try the following for factorial :n.
Removing 'comments', speeds it. The size of the numbers (:p) that 'Remainder
can deal with is one limitation.
Type procs to edit.
Regards
Mike
---------
to factorial :n
;big numbers are packed into a list
;from least to most significant.
localmake "p 6 ;number of digits per list element
localmake "p10 power 10 :p
localmake "start timemilli
big.print fact :n
show timemilli-:start
end
to fact :n ;op in list form
if :n=0[op s.mult 1 [1] stop]
op s.mult :n fact :n-1 ;multiplication with big numbers
end
to s.mult :k :num.l ;multiply list elements by :k with carry
localmake "num 0
localmake "carry 0
op hs.mult :num.l
end
to hs.mult :num.l
if empty? :num.l[ifelse :carry=0~
[[]stop]~
[(list :carry)stop]] ;deals with final carry
make "num :k*(first :num.l)+:carry
make "carry 0
if (or :num>:p10 :num=:p10)~
[make "carry int :num/:p10]
op fput (remainder :num :p10) hs.mult bf :num.l
end
to pack :n ;add 0's to front of list element
localmake "num :n
repeat (:p-(count :n))[make "num word 0 :num]
op :num
end
to big.print :num.l ;reverse prints list
hbig.print :num.l
pr "\
end
to hbig.print :num.l
if empty? :num.l[stop]
hbig.print bf :num.l
type pack first :num.l
end
to procs
ed[factorial fact s.mult hs.mult pack big.print hbig.print procs]
end
-------
---------------------------------------------------------------
Please post messages to the Logo forum to logo-l@gsn.org. Mail
questions about the list administration to logofdn@gsn.org. To
unsubscribe send unsubscribe logo-l to majordomo@gsn.org.
Global SchoolNet Foundation -
Linking Kids Around the World!
Copyright GSN - All Rights Reserved
- Comments
& Questions
Visit GSN's
Global
Schoolhouse for more exciting learning resources!
Search our Site
-
Home