euler/crystal/euler.cr

67 lines
1.2 KiB
Crystal

# miscellaneous stuff
require "big"
module Euler
extend self
alias NumType = Int32 | Int64 | UInt32 | UInt64
macro trial_division_method(given_type)
def trial_division(n : {{given_type}})
factors = [] of {{given_type}}
check = ->(p: {{given_type}}) {
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
end
trial_division_method(NumType)
trial_division_method(BigInt)
def prime_factorization(n : NumType | BigInt)
result = {} of (NumType | BigInt) => Int32
factors = self.trial_division(n)
factors.each do |f|
result[f] = 0
num = n
while num % f == 0
result[f] += 1
num /= f
end
end
result
end
def to_big_ints(num_list : Array(NumType))
num_list.map { |n| BigInt.new(n) }
end
def to_digit_list(n : NumType | BigInt)
n.to_s.chars.map { |d| d.to_i }
end
def palindrome?(x)
x.to_s.reverse == x.to_s
end
end