コラッツ・角谷の問題
Posted feedbacks - Common Lisp
とりあえず書いたって感じですが。CLISP で約9秒。
1 2 3 4 5 6 7 8 9 10 11 12 | (defun collatz (n)
(let ((memo (make-hash-table)))
(setf (gethash 1 memo) 1)
(labels ((collatz-loop (i)
(cond ((gethash i memo))
((evenp i)
(setf (gethash i memo) (1+ (collatz-loop (/ i 2)))))
(t
(setf (gethash i memo) (1+ (collatz-loop (1+ (* 3 i)))))))))
(loop with max = 0 and j for i from 1 to n as x = (collatz-loop i)
if (< max x) do (setf max x j i)
finally (format t "max ~D for n=~D~%" max j)))))
|
SBCL 1.0.13 x86_64 / Linux / Core2 E6600 2.4GHzで、2〜3秒でした。 (time (collatz-max (expt 2 20))) ;=> f(837799) = 524 ; ;Evaluation took: ; 1.355 seconds of real time ; 2.672167 seconds of user run time ; 0.0 seconds of system run time ; 0 calls to %EVAL ; 0 page faults and ; 1,728 bytes consed.
1 2 3 4 5 6 7 8 9 10 11 12 | (defun collatz (n)
(do ((cnt 0 (1+ cnt))
(res n (if (evenp res) (ash res -1) (1+ (* res 3)))))
((= 1 res) cnt)
(declare (fixnum cnt res n))))
(defun collatz-max (num)
(do ((i 1 (1+ i)) (n 0) (highest 0))
((> i num) (format t "f(~D) = ~D~%" n highest))
(let ((cur (collatz i)))
(when (< highest cur)
(setq n i highest cur)))))
|


ところてん
#4969()
Rating2/2=1.00
see: コラッツの問題の成り立つ範囲
[ reply ]