fork download
  1. ; leading digits of powers of 2
  2.  
  3. (display (expt 2 32)) (newline)
  4.  
  5. (define (leading-digit two-to-n) ; slow
  6. (- (char->integer (string-ref
  7. (number->string (expt 2 two-to-n)) 0)) 48))
  8.  
  9. (display (leading-digit 32)) (newline)
  10.  
  11. (define (leading-digit two-to-n) ; fast
  12. (let* ((q (* (log10 2) two-to-n))
  13. (r (- q (truncate q))))
  14. (let loop ((i 2))
  15. (if (< r (log10 i)) (- i 1)
  16. (loop (+ i 1))))))
  17.  
  18. (display (leading-digit 32)) (newline)
  19.  
  20. (define (lead2 n)
  21. (let ((counts (make-vector 10 0)))
  22. (do ((i 0 (+ i 1))) ((= i n) counts)
  23. (let ((d (leading-digit i)))
  24. (vector-set! counts d
  25. (+ (vector-ref counts d) 1))))))
  26.  
  27. (display (lead2 100000)) (newline)
Success #stdin #stdout 2.91s 44384KB
stdin
Standard input is empty
stdout
4294967296
4
4
#(0 30103 17611 12492 9692 7919 6695 5797 5116 4575)