Thursday, August 13, 2009

Euler Project Six

The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.


My Solution

(defun enumerate-interval (low high) 
   (loop for i from low to high 
      collect i))

(apply #'+ (mapcar #'(lambda (x)(* x x)) (enumerate-interval 1 100)))

(apply #'+ (enumerate-interval 1 100))


Others' Solution

One Solution

(defun square-diff (limit) 
(let (diff) 
(loop for i from 1 to limit 
sum i into nums 
sum (* i i) into squares 
finally (setq diff (- (* nums nums) squares))) 
diff)) 


Two Solution

(defun list-naturals (max)
(do ((x max (1- x))
(list '() (cons x list)))
((= x 0) list)))
 
(let ((N (list-naturals 100))
(square #'(lambda (x) (* x x))))
(- (funcall square (apply #'+ N)) (apply #'+ (map 'list square N))))


Three Solution

(- (expt (apply #'+ (loop for i from 1 to 100 collect i)) 2) 
(apply #'+ (loop for i from 1 to 100 collect (* i i)))) 


No comments:

Post a Comment