问题描述:
The sum of the squares of the first ten natural numbers is,
1
2+ 2
2+ ... + 10
2= 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)
2= 55
2= 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
(ns euler-problem-6.core
(:use [clojure.contrib.math]))
(defn square
[num]
(* num num))
(square 3)
(defn square-sum-version-1
[num]
(loop
[current-num 1M sum 0M]
(if (= current-num num)
(+ sum (square current-num))
(recur (inc current-num) (+ sum (square current-num))))))
(defn square-sum-version-2
[num]
(reduce + (map square (range 1M (inc num)))))
;(time (square-sum-version-1 1000000M))
;(time (square-sum-version-2 1000000M))
(defn sum-square-version-1
[num]
(loop
[current-num 1M add-sum 0M]
(if (= current-num num)
(square (+ add-sum current-num))
(recur (inc current-num) (+ current-num add-sum)))))
(defn sum-square-version-2
[num]
(square (reduce + (range 1M (inc num)))))
;(sum-square-version-1 10)
;(sum-square-version-2 10)
(defn dif-sum-square-with-square-sum
[num]
(abs (- (sum-square-version-1 num) (square-sum-version-1 num))))
(dif-sum-square-with-square-sum 100M)
经测试,尾递归版本的性能要好于延迟加载的版本,但是延迟加载程序简单明了!