Skip to content

Instantly share code, notes, and snippets.

@joshuaclayton
Created June 16, 2009 02:12
Show Gist options
  • Save joshuaclayton/130482 to your computer and use it in GitHub Desktop.
Save joshuaclayton/130482 to your computer and use it in GitHub Desktop.
# Problem 1: 234168
(1..1000).select {|i| i % 3 == 0 || i % 5 == 0}.inject(:+)
# Problem 2: 4613732
def fib(x)
return 0 if x == 0
cache = Array.new(x)
cache[0], cache[1] = 0, 1
2.upto(x) do |i|
cache[i] = cache[i - 1] + cache[i - 2]
end
cache[x]
end
i, result = 1, 0
while i > 0
fib_number = fib(i)
result += fib_number if fib_number % 2 == 0
break if fib_number > 4_000_000
i += 1
end
# Problem 7: 104743
# wrote a sieve in Ruby; assume that approx. 10% of a given number n are prime, so we'll overestimate a bit and just grab the 10001st
def sieve(n)
numbers = (0..n).map
numbers[0] = numbers[1] = nil
numbers.each do |num|
next unless num
break if num**2 > n
# start at num**2 since all previous multiples (n - (n - 1), n - (n - 2), etc) have been removed
(num**2).step(n, num) {|idx| numbers[idx] = nil }
end
numbers.compact
end
sieve(120000)[10000]
# Problem 8: 40824
num = %(73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450).gsub(/\s/, '')
num.scan(/[7-9]{5}/).map {|i| i.split(//).map(&:to_i).inject(:*) }.sort.last
# Problem 16: 1366
(2**1000).to_s.split(//).map(&:to_i).inject(:+)
# Problem 20: 648
def factorial(n)
raise ArgumentError if n.to_i < 0
return 1 if n.to_i == 0
(1..n.to_i).inject(:*)
end
factorial(100).to_s.split(//).map(&:to_i).inject(:+)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment