(defconstant +mod+ 1000000007) (defun %mod-fibonacci (n m) (labels ((rec (a b i p q) (cond ((zerop i) (mod b m)) ((evenp i) (rec a b (floor i 2) (mod (+ (* p p) (* q q)) m) (mod (+ (* 2 p q) (* q q)) m))) (t (rec (mod (+ (* b q) (* a q) (* a p)) m) (mod (+ (* b p) (* a q)) m) (1- i) p q))))) (rec 1 0 n 0 1))) (defun %mod-mat-mul (a b m) (let ((res (make-array (list 3 3) :element-type 'integer :initial-element 0))) (dotimes (i 3) (dotimes (j 3) (dotimes (k 3) (incf (aref res i j) (mod (* (aref a i k) (aref b k j)) m))))) res)) (defun %mod-mat-pow (a n m) (let ((res (make-array (list 3 3) :element-type 'integer))) (dotimes (i 3) (dotimes (j 3) (setf (aref res i j) (if (= i j) 1 0)))) (loop while (not (zerop n)) when (oddp n) do (setf res (%mod-mat-mul a res m)) do (setf a (%mod-mat-mul a a m)) (setf n (floor n 2))) res)) (defun main (&rest argv) (declare (ignorable argv)) (let* ((n (read)) (m (read)) (a (%mod-fibonacci (1+ m) +mod+)) (b (%mod-fibonacci m +mod+)) (c (%mod-fibonacci m +mod+)) (d (%mod-fibonacci (1- m) +mod+)) (e (make-array (list 3 3) :element-type 'integer :initial-element 0))) (setf (aref e 0 0) a (aref e 0 1) b (aref e 1 0) c (aref e 1 1) d (aref e 2 1) 1 (aref e 2 2) 1) (format t "~d~%" (mod (aref (%mod-mat-pow e (1+ n) +mod+) 2 0) +mod+)))) (main)