Refactoring

This commit is contained in:
David Doblas Jiménez 2022-10-22 16:34:53 +02:00
parent f3b932a04e
commit 4f53fc814d

View File

@ -8,18 +8,40 @@ Solution for Problem 21 of Project Euler
https://projecteuler.net/problem=21 =# https://projecteuler.net/problem=21 =#
using BenchmarkTools using BenchmarkTools
using Primes
function divisors(n)
divisors = Int64[1] function sum_divisors(n)
m = round(Int, n / 2) counter = 1
for i in 2:m factors = factor(n)
if n % i == 0 factors_keys = keys(factors)
push!(divisors, i)
for i in factors_keys
count = 1
for j = 1:factors[i]
count += i^j
end end
counter *= count
end end
return divisors
return counter - n
end end
function is_amicable(n)
s = sum_divisors(n)
if s == n
return false
end
sum_s = sum_divisors(s)
if sum_s == n
return true
end
return false
end
function Problem21() function Problem21()
#= #=
Let d(n) be defined as the sum of proper divisors of n (numbers Let d(n) be defined as the sum of proper divisors of n (numbers
@ -33,20 +55,14 @@ function Problem21()
Evaluate the sum of all the amicable numbers under 10000 =# Evaluate the sum of all the amicable numbers under 10000 =#
n = 9999 counter = 0
s = zeros(Int, n) for i = 2:10_000
amicable = Int64[] if is_amicable(i)
for i in 2:n counter += i
s[i] = sum(divisors(i))
end
for i in 2:n
if s[i] <= n && i != s[i] && i == s[s[i]]
push!(amicable, i)
end end
end end
return sum(amicable) return counter
end end