[racket] a small programming exercise

From: Robby Findler (robby at eecs.northwestern.edu)
Date: Thu Oct 14 20:25:17 EDT 2010

Remainder is probably the one you want.

Robby

On Thursday, October 14, 2010, Joe Marshall <jmarshall at alum.mit.edu> wrote:
> Here's an interesting data point.
>
> (define (first-digit-fast-1 n)
>  (if (> 10 n)
>      n
>      (let loop ((i 10)
>                 (next 100))
>        (if (> next n)
>            (first-digit-fast (floor (/ n i)))
>            (loop next (* i i))))))
>
> This takes about 13 seconds on my work machine.
>
> If I take advantage of the types:
>
> (define (first-digit-fast-2 n)
>  (if (and (fixnum? n)
>           (fix:> 10 n))
>      n
>      (let loop ((i 10)
>                 (next 100))
>        (if (int:> next n)
>            (first-digit-fast (int:quotient n i))
>            (loop next (int:* i i))))))
>
> This takes about 3 seconds.
>
> I think the culprit is the call to (floor (/ n i))
> The division will allocate an unnecessary rational.  The int:quotient
> primitive doesn't need to.
>
> I'm pretty sure that Racket has some similar primitives.
>
> --
> ~jrm
> _________________________________________________
>   For list-related administrative tasks:
>   http://lists.racket-lang.org/listinfo/users
>


Posted on the users mailing list.