Problem 1: Multiples of 3 and 5

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.測試

Find the sum of all the multiples of 3 or 5 below 1000.spa

用窮舉法暴力解答

第一道題老是很是簡單的,只是求 1000 如下全部 3 或 5 的倍數之和。直接在 Haskell 交互環境中輸入如下語句就好了:code

Prelude> sum [ x | x <- [1..999], mod x 3 == 0 || mod x 5 == 0 ]
233168

這是用窮舉法來測試 1000 如下的全部正整數,再將全部 3 或 5 的倍數相加就好了。blog

使用組合數學公式解答

根據組合數學的容斥原理,這道題的答案是:ip

1

根據等差數列的求和公式,咱們有:ci

2

根據以上公式,咱們寫出如下 Haskell 程序 001.hs:get

import System.Environment

main = do
  s <- getArgs
  print $ let n = read $ head s in (f n 3) + (f n 5) - (f n 15)

f x y = let n = div x y in y * div (n * (n + 1)) 2

運行後獲得一樣的結果:數學

$ runhaskell 001 999
233168

雖然程序看上去更復雜了,可是其效率卻大大地提升了。前一個程序的時間複雜度是 O(n),而這個程序的時間複雜度是 O(1)。也就是說,無論 n 多麼大,均可以立刻算出結果。例如,把 n 的值改爲一個很是大的數,這個程序瞬間就能夠計算出結果:io

$ runhaskell 001 999999999999999999999999999999999999999999999999999999999999999999999999999
233333333333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666666666668

使用這些公式,也很容易使用紙和筆進行計算。class

還能夠參閱:001_overview.pdf

相關文章
相關標籤/搜索