From 9cc30f5f84806c63beef2faa6fbfae73bf007367 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Doblas=20Jim=C3=A9nez?= Date: Thu, 5 Aug 2021 17:01:52 +0200 Subject: [PATCH] Solution to problem 21 in Julia --- src/Julia/Problem021.jl | 55 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/Julia/Problem021.jl diff --git a/src/Julia/Problem021.jl b/src/Julia/Problem021.jl new file mode 100644 index 0000000..ca7f164 --- /dev/null +++ b/src/Julia/Problem021.jl @@ -0,0 +1,55 @@ +#= +Created on 05 Aug 2021 + +@author: David Doblas Jiménez +@email: daviddoji@pm.me + +Solution for Problem 21 of Project Euler +https://projecteuler.net/problem=21 =# + + +function divisors(n) + divisors = Int64[1] + m = round(Int, n / 2) + for i in 2:m + if n % i == 0 + push!(divisors, i) + end + end + return divisors +end + +function Problem21() + #= + Let d(n) be defined as the sum of proper divisors of n (numbers + less than n which divide evenly into n). + If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable + pair and each of a and b are called amicable numbers. + + For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, + 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are + 1, 2, 4, 71 and 142; so d(284) = 220. + + Evaluate the sum of all the amicable numbers under 10000 =# + + n = 9999 + s = zeros(Int, n) + amicable = Int64[] + for i in 2:n + 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 + + return sum(amicable) +end + + +println("Time to evaluate Problem 21:") +@time Problem21() +println("") +println("Result for Problem 21: ", Problem21()) \ No newline at end of file