[ create a new paste ] login | about

Project: programmingpraxis
Link: http://programmingpraxis.codepad.org/Oz8Rt3EA    [ raw code | output | fork ]

programmingpraxis - Scheme, pasted on Feb 25:
; an odd way to square

(define (square n)
  (let loop ((x n) (s 0))
    (if (zero? x) (+ s s (- n))
      (loop (- x 1) (+ s x)))))

(display (square 4)) (newline)
(display (square 100)) (newline)

(define (square n)
  (if (zero? n) 0
    (+ (square (- n 1)) n n -1)))

(display (square 4)) (newline)
(display (square 100)) (newline)

(define (square n)
  (let loop ((x n) (y n) (s 0))
    (cond ((zero? x) s)
          ((odd? x) (loop (quotient x 2) (* y 2) (+ s y)))
          (else (loop (quotient x 2) (* y 2) s)))))

(display (square 4)) (newline)
(display (square 100)) (newline)


Output:
1
2
3
4
5
6
16
10000
16
10000
16
10000


Create a new paste based on this one


Comments: