|
# 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 编辑 ] |
|