51Testing软件测试论坛

标题: http://projecteuler.net/网站试题 ruby实现 Problem 1~~3 [打印本页]

作者: Spark.lee    时间: 2009-9-8 10:27
标题: 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[n - 1] + $stack[n - 2]
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
给你一个更有趣的
http://www.rubyquiz.com/
作者: Spark.lee    时间: 2009-9-8 21:27
标题: 这个是做什么的 啊

作者: 小米啊    时间: 2009-9-9 09:30
学习 ruby呀!看了一下午才弄明白第一个算法.
作者: Spark.lee    时间: 2009-9-10 13:49
标题: 你是在看我写的吗
呵呵 把你写的拿出来看看哦




欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2