介绍一个做题网站

介绍一个做题网站

http://projecteuler.net/index.php?section=problems
-----------------------------------------------------------------------------------------
目前共有178个题, 第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.
-------------------------------------------------------------------------------------

我的答案是这样的,

max = 1000
sum = 0
m3 = 0
m5 = 0
m15 = 0
sum += m3 while (m3 += 3) < max
sum += m5 while (m5 += 5) < max
sum -= m15 while (m15 += 15) < max
puts sum

-------------------------------------------------------------------
解出来以后你可以去论坛看别人的源码

比如用PYTHON的
using list comprehension in python:
>>> sum([x for x in range(1000) if x % 3== 0 or x % 5== 0])
233168

---------------------------------------------------------------------------------------
排名前1000里翻了前面几页, 中国人极少, 越南的倒有好多.
这是论坛上比较有RUBY味的解法

def sum_multiples(ary, range)
range.inject(0) do |sum, n|
ary.any? { |i| n % i == 0 } ? sum + n : sum
end
end

puts sum_multiples([3,5], 0..999)
这个也非常好

puts (3..999).to_a.reject{|n| n%3!=0 and n%5!=0}.inject{|sum,n|sum+n}
还有这个

puts (1...1000).inject(0) { |s, n| (s + n if (n%3).zero? or (n%5).zero?) or s }
喜欢,不错的地方
第4题
-----------------------------------------------------
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.
-----------------------------------------------------
我的解法
class Fixnum
    def palindromic?
        self.to_s.reverse == self.to_s
    end
end
from = 999
to = 100
max = 0
while from > to do
    from.downto(to) do |i|
        if (from * i).palindromic?
            max = from * i if max < from * i
            to = i
            break
        end
    end
    from -= 1
end
puts max

这儿如果数字太大了, 超过了Fixnum的范围, 这个就有些麻烦了, 还是直接判比较好
-------------------------------------------------------
另一中国人的解法

class Fixnum
 def palindromic?
  s = self.to_s
  s.reverse == s
 end
end

t = Time.now
num = 0
999.downto(100) do |i|
 999.downto(i) do |j|
  if (i*j).palindromic? and i*j>num
  puts i, j, num = i*j
  break
  end
 end
end

puts "Time: #{Time.now - t}s"
puts "Answer: #{ num }."
-------------------------------------------------
没我的快, :)
第4题最后一个不就是我的答案吗?

[Copy to clipboard] [ - ]
嘿嘿, 我做的时候你的答案还没在上面呢.

第10题, 求1_000_000以内的所有素数和. 一个美国人的程序飞快, 在我的机上跑只要4秒的, 而我最快的也要44秒.
他用一个一百万的布尔数组, 初始化为真, 然后从2开始写假...

程序在这儿

[Copy to clipboard] [ - ]


[Copy to clipboard] [ - ]
原来楼上就是chaofan啊