読者です 読者をやめる 読者になる 読者になる

ProjectEuler 1-10 Ruby

#!/usr/bin/ruby
require "rational"

def p1
  p (0...1000).select {|i|i%3==0||i%5==0}.inject(0) {|a,b|a+b}
end

def p2
  a,b = 1,1
  sum = 0
  while b<=4000000
    sum += b if b%2==0
    a,b = b,a+b
  end
  p sum
end

def p3
  a=600851475143;(2..a).each{|i|i<a or break;a/=i while a%i==0};p a
end

def p4
  ans = 0
  1000.downto(0) do|i|
    1000.downto(0) do|j|
      a = i*j
      break if a<ans
      ans = a if a.to_s == a.to_s.reverse
    end
  end
  p ans
end

def p5
  p (1..20).inject(1) {|i,j|i.lcm(j)}
end

def p6
  p (1..100).inject(0) {|i,j|i+j}**2 - (1..100).collect {|i|i**2}.inject(0) {|i,j|i+j}
end

def p7
  ma = 105000
  a = Array.new(ma)
  c = 0
  (2..ma).each do|i|
    unless a[i]
      c += 1
      p i or break if c == 10001
      (2*i..ma).step(i) do|j|
        a[j] = true
      end
    end
  end
end

def p8
  data = <<EOD
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
EOD

  a = data.scan(/\d/).collect &:to_i
  b = ([1]*(a.size+1-5)).zip(*(0...5).collect {|i|a[i...a.size]}).collect{|i|i.inject(1){|i,j|i*j}}.max
  p b
end

def p9
  ans = nil
  (1..1000).each do|a|
    (a+1..1000).each do|b|
      c = 1000 - a - b
      break unless b < c
      ans = a*b*c if a*a+b*b==c*c
      break if ans
    end
    break if ans
  end
  p ans
end

def p10
  a = Array.new(2000001)
  sum = 0
  (2..2000000).each do|i|
    unless a[i]
      sum += i
      (0..2000000).step(i) do|j|
        a[j]=true
      end
    end
  end
  p sum
end



(1..10).each do |i|
  print "p#{i}: "
  method("p#{i}").call
end