• entries
18
21
• views
12294

# Lisp

449 views

Well, I'm back and I've been reading this. I never remember a language unless I use it so I pulled out C++ Primer Plus and looked for an exercise as my first program. I decided to go with something very simple that nevertheless took me a depressingly long time to write: A program that prints the sum of all the numbers between two supplied values.

Here is the result:
(defun sum-between2 (x y &optional (verb 0))  "sum all numbers between suplied vars together - prettier version"  (when (> x y) (rotatef x y)) ;if x > y then sum-between2 (y x)  (let ((sum 0) (iter x)) ;sum = 0  (dotimes (- y x)    (setf sum (+ iter sum))    (incf iter))  (format t "The sum of the numbers between ~[~d~;~r~] and ~[~d~;~r~] is ~[~d~;~r~]~%" verb x verb y verb sum)  sum))

And because this was painfully slow I just had to optimise it into this shorter program:
(defun sum-between-fast ( x y &optional (verb 0))  "sum all numbers between suplied vars together fast"  (when (> x y) (rotatef x y))  (let ((sum 0))  (setf sum (/ (* (1+ (- y x)) (+ x y)) 2))  (format t "The sum of the numbers between ~[~d~;~r~] and ~[~d~;~r~] is ~[~d~;~r~]~%" verb x verb y verb sum)  sum))

Here is some output:
CL-USER> (sum-between-fast 1 5)The sum of the numbers between 1 and 5 is 1515

CL-USER> (sum-between-fast 1 5 1)The sum of the numbers between one and five is fifteen15

And for kicks:

CL-USER> (sum-between-fast 1 215478654 1)The sum of the numbers between one and two hundred and fifteen million, four hundred and seventy-eight thousand, six hundred and fifty-four is twenty-three quadrillion, two hundred and fifteen trillion, five hundred and twenty-five billion, two hundred and seventy-two million, five hundred and sixty-five thousand, one hundred and eighty-five23215525272565185

I love ~r. [smile]

Feel free to criticise anything.

There are no comments to display.

## Create an account

Register a new account