2014-11-20 19:38:31 +00:00
|
|
|
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)
|
2014-11-20 19:38:31 +00:00
|
|
|
end
|
2014-11-20 21:54:55 +00:00
|
|
|
|
|
|
|
def factorial
|
2018-02-21 21:00:08 +00:00
|
|
|
(2..self).inject(:*)
|
2014-11-20 21:54:55 +00:00
|
|
|
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
|
2014-11-20 19:38:31 +00:00
|
|
|
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
|
|
|
|
|
2016-09-06 07:08:56 +00:00
|
|
|
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
|
|
|
|
|
2014-11-20 19:38:31 +00:00
|
|
|
end
|
|
|
|
end
|