euler/crystal/euler.cr

82 lines
1.6 KiB
Crystal
Raw Normal View History

# miscellaneous stuff
2018-02-23 04:53:01 +00:00
require "big"
module Euler
2018-02-25 03:32:39 +00:00
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}}) {
2018-02-23 04:53:01 +00:00
q, r = n.divmod(p)
2018-02-25 03:32:39 +00:00
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
2018-02-23 04:53:01 +00:00
end
2018-02-25 03:32:39 +00:00
factors << n if n > 1
factors
2018-02-23 04:53:01 +00:00
end
end
2018-02-25 03:32:39 +00:00
macro prime_factorization_method(given_type)
def prime_factorization(n : {{given_type}})
result = {} of {{given_type}} => Int32
factors = self.trial_division(n)
2018-02-23 04:53:01 +00:00
2018-02-25 03:32:39 +00:00
factors.each do |f|
result[f] = 0
num = n
while num % f == 0
result[f] += 1
num /= f
end
end
2018-02-25 03:32:39 +00:00
result
end
end
2018-02-25 03:32:39 +00:00
macro to_digit_list_method(given_type)
def to_digit_list(n : {{given_type}})
n.to_s.chars.map { |d| d.to_i }
end
end
2018-02-23 04:53:01 +00:00
2018-02-25 03:32:39 +00:00
macro to_big_ints_method(given_type)
def to_big_ints(num_list : Array({{given_type}}))
num_list.map { |n| BigInt.new(n) }
end
2018-02-23 04:53:01 +00:00
end
2018-02-25 03:32:39 +00:00
trial_division_method(NumType)
trial_division_method(BigInt)
prime_factorization_method(NumType)
prime_factorization_method(BigInt)
to_digit_list_method(NumType)
to_digit_list_method(BigInt)
to_big_ints_method(NumType)
to_big_ints_method(BigInt)
def palindrome?(x)
x.to_s.reverse == x.to_s
2018-02-23 04:53:01 +00:00
end
end