(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)))))
kozima
#5088()
[
Common Lisp
]
Rating0/0=0.00
とりあえず書いたって感じですが。CLISP で約9秒。
(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)))))Rating0/0=0.00-0+
1 reply [ reply ]