Find the largest palindrome made from the product of two 3-digit numbers.
找到能表示成两个三位数乘积的最大的回文数。
思路就是遍历所有三位数的乘积判断是不是回文数,再选出最大的来
result = 0 999.downto(100) do |x| 999.downto(100) do |y| if (x * y).to_s.reverse == (x * y).to_s result = [result, x*y].max end end end p result
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
这不就是求1到20的最小公倍数么。。。
最小公倍数懒得写了直接用mathn的(mathn好强大,什么都有)
(1..20).inject(1) { |result, n| result.lcm n }
What is the largest prime factor of the number 600851475143
分解质因数在mathn库里已经有现成的了,所以这题相当与白送的
600851475143.prime_division.flatten.max
如果想自己写分解质因数也行啊,自己以前写的速度还比mathn的快~^_^
http://xavier.is-programmer.com/2009/8/15/prime-division.10461.html
Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
找出所有小于4百万的Fibonacci数列中所有奇数项的和
fib = Hash.new {|h,n| n < 2 ? h[n] = n : h[n] = h[n-1] + h[n-2] } s, n = 0, 1 while fib[n] < 4_000_000 s += fib[n] if fib[n] % 2 != 0 n += 1 end p s #=> 4613732
其中用一个hash来生成fibonacci数列是很久以前从网上看到的,当时非常震惊,立马就记住了