28 lines
444 B
Crystal
28 lines
444 B
Crystal
|
alias NumType = Int32 | Int64 | UInt32 | UInt64
|
||
|
|
||
|
def 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
|
||
|
|
||
|
puts trial_division(600851475143).max
|