Solution to problem 44 in Julia

This commit is contained in:
David Doblas Jiménez 2021-09-14 18:55:33 +02:00
parent 91b1f5c442
commit 20c35a6140

51
src/Julia/Problem044.jl Normal file
View File

@ -0,0 +1,51 @@
#=
Created on 14 Sep 2021
@author: David Doblas Jiménez
@email: daviddoji@pm.me
Solution for Problem 44 of Project Euler
https://projecteuler.net/problem=44
=#
using BenchmarkTools
using Combinatorics
function pentagonal(n)
return Int(n*(3*n-1)/2)
end
function Problem44()
#=
Pentagonal numbers are generated by the formula, Pn=n(3n1)/2.
The first ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their
difference, 70 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their
sum and difference are pentagonal and D = |Pk Pj| is minimised.
What is the value of D?
=#
dif = 0
pentagonal_list = [pentagonal(n) for n in 1:2500]
pairs = combinations(pentagonal_list, 2)
for p in pairs
if reduce(+, p) in pentagonal_list && abs(reduce(-, p)) in pentagonal_list
dif = (abs(reduce(-,p)))
# the first one found would be the smallest
break
end
end
return dif
end
println("Time to evaluate Problem 44:")
@btime Problem44()
println("")
println("Result for Problem 44: ", Problem44())