(declaim (optimize (speed 3) (safety 0) (debug 0)))

(defconstant +loop-count+ 1000000)
(defconstant +expected-checksum+ 1185071)

(declaim (ftype (function () fixnum) configured-loop-count))
(defun configured-loop-count ()
  (handler-case
      (let ((line (read-line *standard-input* nil nil)))
        (if line
            (let ((value (parse-integer line :junk-allowed t)))
              (if (> value 0) value +loop-count+))
            +loop-count+))
    (error () +loop-count+)))

(declaim (ftype (function (fixnum) fixnum) branch-loop))
(defun branch-loop (limit)
  (declare (type fixnum limit))
  (loop with i of-type fixnum = 0
        with acc of-type fixnum = 7
        while (< i limit)
        do (let* ((bounded (if (> acc 1000000000)
                               (- acc 1000000000)
                               acc))
                  (branched (if (< i 500000)
                                (+ bounded 3)
                                (+ bounded 7)))
                  (next (if (> branched 1234567)
                            (- branched 1234567)
                            (+ branched 11))))
             (declare (type fixnum bounded branched next))
             (setf acc next
                   i (+ i 1)))
        finally (return acc)))

(let ((result (branch-loop (configured-loop-count))))
  (format t "~D~%" result)
  (sb-ext:exit :code (if (= result +expected-checksum+) 0 1)))
