2018-02-21 23:07:31 +00:00
|
|
|
# miscellaneous stuff
|
|
|
|
|
2018-02-23 04:53:01 +00:00
|
|
|
require "big"
|
|
|
|
|
2018-02-21 23:07:31 +00:00
|
|
|
module Euler
|
2018-02-23 04:53:01 +00:00
|
|
|
alias NumType = Int32 | Int64 | UInt32 | UInt64 | BigInt
|
|
|
|
|
|
|
|
def self.trial_division(n : NumType)
|
|
|
|
factors = [] of NumType
|
|
|
|
check = ->(p: NumType) {
|
|
|
|
q, r = n.divmod(p)
|
|
|
|
while r.zero?
|
|
|
|
factors << p
|
|
|
|
n = q
|
|
|
|
q, r = n.divmod(p)
|
|
|
|
end
|
|
|
|
}
|
|
|
|
|
|
|
|
check.call(2)
|
|
|
|
check.call(3)
|
|
|
|
p = 5
|
|
|
|
while p * p <= n
|
|
|
|
check.call(p)
|
|
|
|
p += 2
|
|
|
|
check.call(p)
|
|
|
|
p += 4
|
|
|
|
end
|
|
|
|
factors << n if n > 1
|
|
|
|
factors
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.prime_factorization(n : NumType)
|
|
|
|
result = {} of NumType => NumType
|
|
|
|
factors = self.trial_division(n)
|
|
|
|
|
|
|
|
factors.each do |f|
|
|
|
|
result[f] = 0
|
|
|
|
num = n
|
|
|
|
while num % f == 0
|
|
|
|
result[f] += 1
|
|
|
|
num /= f
|
2018-02-21 23:07:31 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-02-23 04:53:01 +00:00
|
|
|
result
|
2018-02-21 23:07:31 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.palindrome?(x)
|
|
|
|
x.to_s.reverse == x.to_s
|
|
|
|
end
|
2018-02-23 04:53:01 +00:00
|
|
|
|
|
|
|
def self.to_digit_list(n : NumType)
|
|
|
|
n.to_s.chars.map { |d| d.to_i }
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.to_big_ints(num_list : Array(NumType))
|
|
|
|
num_list.map { |n| BigInt.new(n) }
|
|
|
|
end
|
2018-02-21 23:07:31 +00:00
|
|
|
end
|