Lisp - Sum Squares/Square Sums

Project Euler lisp programming

Recently I've been introduced to the Project Euler problems and have been solving them with clisp as an excersie to learn that language. In deference to the rules of Project Euler, I will not post explicit solutions to the problems, nor will I link to a specific problem number. Where possible, I will randomly generate data to use in place of the data in the project prompts.

Difference between the sum of squares and square of sums

Prompt: Given a number n, let the sum of squares equal 12 + 22 + 32 + ... + n2 and let the square of sums equal (1 + 2 + 3 + ... + n)2. For arbitrary n, calculate the difference between the square of sums and the sum of squares.

My code

(defun sum-of-squares (topnum)
  (apply '+ (loop for x from 1 to topnum collecting (expt x 2))))

(defun square-of-sums (topnum)
  (expt (apply '+ (loop for x from 1 to topnum collecting x)) 2))

(defun difference-between-sum-squares-and-square-sums (topnum)
  (- (square-of-sums topnum) (sum-of-squares topnum)))

Previous Post Next Post