euler/ruby/euler.rb

71 lines
1.3 KiB
Ruby

require 'prime'
class Integer
def choose(k)
factorial / (k.factorial * (self - k).factorial)
end
def divisors
[].tap do |divisors|
(1..Math.sqrt(self).to_i).each do |num|
if self % num == 0
divisors << num
divisors << self / num
end
end
end
end
def prime_factors
self.prime_division.map(&:first)
end
def factorial
(2..self).inject(:*)
end
def to_digit_list
self.to_s.split('').map(&:to_i)
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
def non_empty_subsets(list)
(1..list.count).map { |x| list.combination(x).to_a }.flatten(1)
end
def powerset(list)
(0..list.count).map { |x| list.combination(x).to_a }.flatten(1)
end
end
end