Project Euler

Project Euler是个数学问题求解网站,网站设计的很有意思,有很多problem,在未提交正确答案前不能查看problem的overview,也不能查看关于problem的discussion thread,只能看到现在problem已经被多少人解决了,人数越多往往代表问题越容易。

    看看problem 1吧:

Add all the natural numbers below one thousand that are multiples of 3 or 5.

    简单吧?我的第一个反应用haskell一行就解决了:

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

233168

接着把答案提交,提交后可以看到一个pdf,是关于此题的官方分析,里面思考了算法的效率问题,像上面的haskell代码有什么问题呢?如果要求1000000000里面的数的话上面代码有无问题呢?以及时间复杂度呢?

 

原来可以有更好的解决方法,也不用暴力求解了,答案读者自己登上Project Euler 学习吧!

 

最有意思的是可以看到数学的神奇,看下面:

 

Prelude> sum [x|x<-[1..10-1], x `mod` 3 == 0 || x `mod` 5 == 0]         
23
Prelude> sum [x|x<-[1..100-1], x `mod` 3 == 0 || x `mod` 5 == 0]
2318
Prelude> sum [x|x<-[1..1000-1], x `mod` 3 == 0 || x `mod` 5 == 0]
233168
Prelude> sum [x|x<-[1..10000-1], x `mod` 3 == 0 || x `mod` 5 == 0]
23331668
Prelude> sum [x|x<-[1..100000-1], x `mod` 3 == 0 || x `mod` 5 == 0]
2333316668
Prelude> sum [x|x<-[1..1000000-1], x `mod` 3 == 0 || x `mod` 5 == 0]
233333166668
 

与这个problem 1类似的就是Fizzbuzz问题。

FizzBuzz的解释如下:

it is a programming exercise in which goal is to list integers from 1 to 100, replacing those divisible by 3 with the term “Fizz,” those divisible by 5 with the term “Buzz,” and those divisible by both 3 and 5 with the term “FizzBuzz.”

 

这个FizzBuzz问题可以用haskell一行解决,如下:

Prelude> [max(show x)(concat[n|(f,n)<-[(3,"Fizz"),(5,"Buzz")],mod x f==0])|x<-[1..100]]
["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz","16","17","Fizz","19","Buzz","Fizz","22","23","Fizz","Buzz","26","Fizz","28","29","FizzBuzz","31","32","Fizz","34","Buzz","Fizz","37","38","Fizz","Buzz","41","Fizz","43","44","FizzBuzz","46","47","Fizz","49","Buzz","Fizz","52","53","Fizz","Buzz","56","Fizz","58","59","FizzBuzz","61","62","Fizz","64","Buzz","Fizz","67","68","Fizz","Buzz","71","Fizz","73","74","FizzBuzz","76","77","Fizz","79","Buzz","Fizz","82","83","Fizz","Buzz","86","Fizz","88","89","FizzBuzz","91","92","Fizz","94","Buzz","Fizz","97","98","Fizz","Buzz"]
 这个不是我想出来的, 看这里

 

你可能感兴趣的:(haskell)