[ prog / sol / mona ]

prog


LISP Puzzles

93 2020-05-17 11:43 *

Here's a Scheme solution using queues to calculate the sequence up to the last relevant "skip" in R values and calculate the "jump" from there.

(use-modules (ice-9 q))

(define (sequence n)
  (let* ((rs (make-q))
         (ss (make-q))
         (r 7)
         (s 5)
         (l 3)
         (n (- n 1)))
    (enq! rs r)
    (enq! ss s)
    (let loop ((i 4))
      (when (<= (+ s r) (+ i n))
        (set! r (+ r s))
        (set! s (+ s 1))
        (when (= s (q-front rs))
          (set! s (+ s 1))
          (set! l (+ l 1))
          (deq! ss)
          (deq! rs))
        (enq! rs r)
        (enq! ss s)
        (loop (+ i 1)))
      (list l rs ss))))

(define (sum m n)
  (* (/ (- m n -1) 2) (+ m n)))

(define (negsum a l)
  (cond
   ((null? l) a)
   (else (negsum (- a (car l)) (cdr l)))))

(define (jump n)
  (cond
   ((= n 1) 1)
   ((= n 2) 3)
   ((= n 3) 7)
   ((= n 4) 12)
   (else
    (let* ((seq (sequence n))
           (p   (caadr seq))
           (l   (length p))
           (n'  (+ (car seq) l -1))
           (s'  (q-rear (caddr seq)))
           (r'  (q-rear (cadr seq)))
           (s   (+ s' (- n n') l)))
      (+ r' (sum (- s 1) s') (negsum 0 p))))))

It starts getting slow at 10^13 (which is 50000029798618763894670256).

157


VIP:

do not edit these