Comment detail

コラッツ・角谷の問題 (Nested Flatten)

とりあえず書いたって感じですが。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)))))

ステップ数をひとつ多く数えてました。

1
2
-    (setf (gethash 1 memo) 1)
+    (setf (gethash 1 memo) 0)

Index

Feed

Other

Link

Pathtraq

loading...