问题描述:
The sum of the squares of the first ten natural numbers is,
12+ 22+ ... + 102= 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2= 552= 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025
385
= 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)
经测试,尾递归版本的性能要好于延迟加载的版本,但是延迟加载程序简单明了!
本文介绍了如何计算前一百自然数的平方和与它们和的平方之间的差值,提供了几种不同的计算方法并比较了它们的性能。包括使用递归和非递归方式实现,以及在不同版本间的效率对比。
148

被折叠的 条评论
为什么被折叠?



