From c8403e627e85aea31cdc2e0b86703d1d3a4ee05b Mon Sep 17 00:00:00 2001 From: daviddoji Date: Wed, 15 Sep 2021 16:28:19 +0200 Subject: [PATCH] Solution to problem 45 in Julia --- src/Julia/Problem045.jl | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/Julia/Problem045.jl diff --git a/src/Julia/Problem045.jl b/src/Julia/Problem045.jl new file mode 100644 index 0000000..50aea45 --- /dev/null +++ b/src/Julia/Problem045.jl @@ -0,0 +1,45 @@ +#= +Created on 15 Sep 2021 + +@author: David Doblas Jiménez +@email: daviddoji@pm.me + +Solution for Problem 45 of Project Euler +https://projecteuler.net/problem=45 +=# + +using BenchmarkTools + +function pentagonal(n) + return Int(n*(3*n-1)/2) +end + +function hexagonal(n) + return Int(n*(2*n-1)) +end + +function Problem45() + #= + Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: + Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ... + Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ... + Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ... + + It can be verified that T285 = P165 = H143 = 40755. + + Find the next triangle number that is also pentagonal and hexagonal. + =# + pentagonal_list = Set(pentagonal(n) for n in 2:100_000) + # all hexagonal numbers are also triangle numbers! + hexagonal_list = Set(hexagonal(n) for n in 2:100_000) + + ans = sort!(collect(intersect(hexagonal_list, pentagonal_list))) + # First one is already known + return ans[2] +end + + +println("Time to evaluate Problem 45:") +@btime Problem45() +println("") +println("Result for Problem 45: ", Problem45()) \ No newline at end of file