Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Write a Lisp program to calculate the sum of the first N positive integers

  1. Oct 22, 2007 #1
    Help!! Please

    I am trying to write a Lisp program to calculate the sum of the first N positive integers where, for example, when N = 6 the sum of the first N = 21

    Any Ideas?
     
  2. jcsd
  3. Oct 22, 2007 #2
    Sure: the sum of the first N numbers is N plus the sum of the first N-1 numbers. That's a very strong hint. Heck, it's pretty much exactly the answer in LISP... :tongue:
     
  4. Oct 22, 2007 #3
    Would it be something like this?

    (defun nsum (n)
    (if (integerp n)
    (if (or (= n 0) (< n 1))
    Please enter the positive integer
    (* n(/ 2(+ n 1))))))

    Regards
     
  5. Oct 22, 2007 #4
    This attempt yields the error: *** Read error: The input could not be tokenized at 2, 2. ***

    > (defun sum (n1 n2)
    “Returns the sum of two positive integers.”
    (assert
    (and (integerp n1) (>= n1 0))
    (n1)
    “N1 must be a nonnegative integer, instead it’s ~S.”
    (n1)
    (assert
    (integerp n2)
    (n2)
    :N2 must be an integer, instead it’s ~S.”
    n2)
    (if (zerop n1) n2
    (sum (1- n1) (1+n2))))
     
  6. Oct 23, 2007 #5
    Even more obvious hint: nsum of n is defined as 0 if n is less than 1, otherwise it is n plus the nsum of (n-1). This is true in English, right? So write exactly that, but in LISP instead of English.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Write a Lisp program to calculate the sum of the first N positive integers
  1. Does LISP exist? (Replies: 15)

Loading...