Square Pyramidal Numbers
March 14, 2017
This is easy; we want the sum of the squares of the first n integers:
> (define (sq-pyr n) (sum (map square (range 1 (+ n 1))))) > (sq-pyr 15) 1240
That won’t work when n is a million; it takes too much time and space. Fortunately, there is a formula for computing the nth square pyramidal number; you might want to look at A000330:
> (define (sq-pyr n) (/ (+ (* 2 n n n) (* 3 n n) n) 6)) > (sq-pyr 15) 1240 > (sq-pyr 1000000) 333333833333500000
You can run the program at http://ideone.com/k1sJUd.
Pages: 1 2