Permalink
Browse files

2 and 3 problems

  • Loading branch information...
1 parent b93abf2 commit a779cc5515971719e89b95e0bf49c28b7949525d @txus committed Jan 9, 2011
Showing with 41 additions and 0 deletions.
  1. +21 −0 2.rb
  2. +20 −0 3.rb
View
21 2.rb
@@ -0,0 +1,21 @@
+# Problem 2
+# 19 October 2001
+#
+# 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, ...
+#
+# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
+
+def fib(n)
+ n < 2 ? n : fib(n-1) + fib(n-2)
+end
+
+i = 0
+array = []
+while (r = fib(i)) < 4_000_000
+ array << r if (r % 2).zero?
+ i += 1
+end
+
+puts array.inject(:+)
View
20 3.rb
@@ -0,0 +1,20 @@
+# Problem 3
+# 02 November 2001
+#
+# The prime factors of 13195 are 5, 7, 13 and 29.
+#
+# What is the largest prime factor of the number 600851475143 ?
+
+ARRAY = []
+def fac(n)
+ return if n == 1
+ i = 2
+ while !(n % i).zero?
+ i += 1
+ end
+ ARRAY << i unless ARRAY.include? i
+ fac n / i
+end
+
+fac 600_851_475_143
+puts ARRAY.last

0 comments on commit a779cc5

Please sign in to comment.