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.
用穷举法暴力解答
第一道题总是非常简单的,只是求 1000 以下所有 3 或 5 的倍数之和。直接在 Haskell 交互环境中输入以下语句就行了:
Prelude> sum [ x | x <- [1..999], mod x 3 == 0 || mod x 5 == 0 ] 233168
这是用穷举法来测试 1000 以下的所有正整数,再将所有 3 或 5 的倍数相加就行了。
使用组合数学公式解答
根据组合数学的容斥原理,这道题的答案是:
根据等差数列的求和公式,我们有:
根据以上公式,我们写出以下 Haskell 程序 001.hs:
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 的值改成一个非常大的数,这个程序瞬间就可以计算出结果:
$ runhaskell 001 999999999999999999999999999999999999999999999999999999999999999999999999999 233333333333333333333333333333333333333333333333333333333333333333333333333166666666666666666666666666666666666666666666666666666666666666666666666668
使用这些公式,也很容易使用纸和笔进行计算。
还可以参阅:001_overview.pdf。