The Kitchen Sink and Other Oddities

Atabey Kaygun

Euler Project #401

Description of the problem

Euler Project, Problem 401 is a number theory question. It asks the reader to calculate the sum m=1nqmq2 modulo 109 for n=1015. In a previous post, I rewrote the sum in a diffent way as q=1nq2nq But even with the reduction, the calculation was out of reach under the 1 minute mark of a generic Project Euler problem.

Mathematical Reduction

Let me recall the theoretical reduction phase: Υ(n,s)=m=1nqmqs I will define the following auxiliary function ν(q,n)={1 if qn0 otherwise Then I can rewrite Υ(n,s) as follows: Υ(n,s)=m=1nq=1mν(q,m)qs Now we can switch the summations Υ(n,s)=q=1nm=anν(q,m)qs=q=1nqs(m=anν(q,m)) Notice that, the inner sum terms are m=q,q+1,,n but the function we sum is non-zero only if m is a multiple of q. This means the sum m=qnν(q,m)=nq. Therefore, Υ(n,s)=q=1nqsnq Take m such that mn and split the sum as Υ(n,s)=q=1m1qsnq+q=mnqsnq=q=1m1qsnq+k=1n/mk n/q=kqs But this can also be written as Υ(n,s)=q=1m1qsnq+n/q=1n/(m1)1qs+n/q=2n/(m1)1qs++n/q=n/mn/(m1)1qs Now, we observe that nqk whenever qnk This means Υ(n,s)=q=1m1qsnq+k=1n/mq=1n/kqsnmq=1nn/(m1)qs For example when n=6 and m=3 the original summation was q=16qs6q=61s+32s+23s+14s+15s+16s Our reduction indicates the sum above equals to 61s+32s+(1s++6s)+(1s+2s+3s)2(1s+2s) which they are.

Implementation with the new reduction

I already implemented the first part of the summation for s=2:

(defun upsilon1 (n &optional (m (1- (truncate (sqrt n)))))
   (let ((res 0))
      (do ((q 1 (1+ q)))
          ((> q m) res)
        (incf res (* q q (truncate n q))))))

As for the second part:

(defun upsilon2 (n &optional (m (truncate (sqrt n))))
  (labels ((sq (n) (* n (1+ n) (1+ (+ n n)) (/ 6))))
     (let* ((a (truncate (/ n m)))
            (res (- (* a (sq (truncate (/ n (truncate (/ n (1- m))))))))))
         (do* ((k 1 (1+ k)))
              ((> k a) res)
           (incf res (sq (truncate (/ n k))))))))

I will not post the answer here. Plus, the lisp implementation I used took about 2 minutes to calculate the result which is twice as long as a generic Euler Project question should take.