euler/ruby/euler.rb

69 lines
1.1 KiB
Ruby
Raw Normal View History

require 'prime'
class Integer
2014-11-20 22:20:39 +00:00
def choose(k)
factorial / (k.factorial * (self - k).factorial)
end
def divisors
2014-12-05 00:50:52 +00:00
[].tap do |divisors|
(1..Math.sqrt(self).to_i).each do |num|
if self % num == 0
divisors << num
divisors << self / num
end
2014-11-20 22:20:39 +00:00
end
end
2014-12-05 00:50:52 +00:00
end
def prime_factors
self.prime_division.map(&:first)
end
2014-11-20 21:54:55 +00:00
def factorial
i = 1
n = self
while (n > 0)
i *= n
n -= 1
end
i
end
2014-11-20 22:20:39 +00:00
def to_digit_list
self.to_s.split('').map(&:to_i)
2014-11-20 21:54:55 +00:00
end
end
module Euler
class << self
def from_digit_list(list)
list.join('').to_i
end
def generate_pythagorean_triples(upper_bound)
[].tap do |triples|
(2..upper_bound).each do |a|
(a..upper_bound).each do |b|
c = Math.sqrt(a**2 + b**2)
triples << [a, b, c.to_i] if c % 1 == 0
end
end
end
end
def palindrome?(n)
num = n.to_s
(0..(num.length-1)/2).each do |i|
if !(num[i] == num[num.length-1-i])
return false
end
end
true
end
end
end