# [racket] Math - factorial.rkt, binomial.rkt and memoization

On Tue, Apr 9, 2013 at 2:51 PM, Laurent <laurent.orseau at gmail.com> wrote:
>* On Tue, Apr 9, 2013 at 2:42 PM, Matthew Flatt <mflatt at cs.utah.edu> wrote:
*>*
*>>* (for/product ([p (in-range (+ m 1) (+ n 1))]) p)
*>*
*>*
*>*
*>* But I don't fully understand why a simple (for/product ([p (in-range 1
*>* (add1 n))]) p) is as fast as the iota variants.
*>*
*
I don't understand either.
FWIW here's the kind of multiplications performed by the doctored version
attached below:
>* (fact 1000000)
*#hash(((fíx fíx fíx) . 48577) ((big big) . 209717) ((fíx big) . 46338)
((fíx fíx) . 646789))
while the for version should be almost all big x big.
====
(define x*-counter 'not-initialized)
(define (x* . args)
(hash-update! x*-counter (map (λ (x)
(if (fixnum? x)
'fíx
'big))
args)
add1
0)
(apply * args))
;; from included; to excluded.
(define (mult from to)
(case (- to from)
((0) 1)
((1) from)
((2) (x* from (+ from 1)))
((3) (x* from (+ from 1) (+ from 2)))
;; ...
(else
(let ((middle (quotient (+ from to) 2)))
(x* (mult from middle) (mult middle to))))))
(define (fact n)
(set! x*-counter (make-hash))
(define f (if (zero? n)
1
(mult 2 (add1 n))))
(values ;f
x*-counter))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20130409/c886ca29/attachment-0001.html>