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

相关文章
相关标签/搜索