First power of 2 that has leading decimal digits of 12: Difference between revisions

Line 1,433:
p(123, 12345) = 3510491
p(123, 678910) = 193060223</pre>
 
=={{header|Racket}}==
 
{{trans|Pascal}}
 
First implementation is an untyped, naive revision of the Pascal algorithm.
But there is a lot of casting between the exact integers an floats. As well as runtime type checking.
 
Then there is the typed racket version, which is stricter about the use of types
(although, I'm not super happy at the algorithm counting using floating-point integers... but it's faster)
 
Compare and contrast...
 
===Untyped Racket===
 
<lang racket>#lang racket
(define (fract-part f)
(- f (truncate f)))
 
(define ln10 (log 10))
(define ln2/ln10 (/ (log 2) ln10))
(define (inexact-p-test L)
(let ((digit-shift (let loop ((L (quotient L 10)) (shift 1))
(if (zero? L) shift (loop (quotient L 10) (* 10 shift))))))
(λ (p) (= L (truncate (* digit-shift (exp (* ln10 (fract-part (* p ln2/ln10))))))))))
 
(define (p L n)
(let ((test? (inexact-p-test L)))
(let loop ((j 1) (n (sub1 n)))
(cond [(not (test? j)) (loop (add1 j) n)]
[(zero? n) j]
[else (loop (add1 j) (sub1 n))]))))
 
(module+ main
(define (report-p L n)
(time (printf "p(~a, ~a) = ~a~%" L n (p L n))))
(report-p 12 1)
(report-p 12 2)
(report-p 123 45)
(report-p 123 12345)
(report-p 123 678910))</lang>
 
{{out}}
 
<pre>p(12, 1) = 7
cpu time: 1 real time: 1 gc time: 0
p(12, 2) = 80
cpu time: 0 real time: 0 gc time: 0
p(123, 45) = 12710
cpu time: 5 real time: 5 gc time: 0
p(123, 12345) = 3510491
cpu time: 439 real time: 442 gc time: 23
p(123, 678910) = 193060223
cpu time: 27268 real time: 27354 gc time: 194</pre>
 
===Typed Racket===
 
<lang racket></lang>
 
{{out}}
<pre></pre>
 
 
=={{header|Raku}}==
569

edits