• Advertisement

0_o

Sign in to follow this  
  • entries
    18
  • comments
    21
  • views
    12136

Lisp

Sign in to follow this  

337 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 15
15



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


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-five
23215525272565185







I love ~r. [smile]

Feel free to criticise anything.
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement