用clojure解決 euler problem 6

問題描述:

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)

經測試,尾遞歸版本的性能要好於延遲加載的版本,但是延遲加載程序簡單明瞭!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章