Spark.lee 发表于 2009-9-8 10:27:49

http://projecteuler.net/网站试题 ruby实现 Problem 1~~3

#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.


def n(a,b)
sum =0
b.upto(a){|n| sum+=n if n % 3 ==0 or n%5 ==0}
return sum
end
p n(999,1)


#   Problem 2
#Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#Find the sum of all the even-valued terms in the sequence which do not exceed four million.


max    =4000000
total= 0
$stack = []

def fib n
if n == 0
    return 1
end
if n == 1
    return 2
end
return $stack + $stack
end

max.times do |i|
$stack = fib i
if $stack > max
    break
end
if $stack & 1 == 0
    total += $stack
end
end
puts total


#   Problem 3
#The prime factors of 13195 are 5, 7, 13 and 29.
#What is the largest prime factor of the number 600851475143 ?


def v(x)
math =Math.sqrt(x).ceil
math.downto 2 do |n|
      if x % n ==0 && v(n)==1
         return n
   end
end
1
end
p v(600851475143) #6857

[ 本帖最后由 Spark.lee 于 2009-9-8 10:30 编辑 ]

小米啊 发表于 2009-9-8 15:52:18

给你一个更有趣的
http://www.rubyquiz.com/

Spark.lee 发表于 2009-9-8 21:27:17

这个是做什么的 啊

小米啊 发表于 2009-9-9 09:30:28

学习 ruby呀!看了一下午才弄明白第一个算法.

Spark.lee 发表于 2009-9-10 13:49:58

你是在看我写的吗

呵呵 把你写的拿出来看看哦
页: [1]
查看完整版本: http://projecteuler.net/网站试题 ruby实现 Problem 1~~3