From 2df31ca1fb71bd627776b8077ce43490328331b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Doblas=20Jim=C3=A9nez?= Date: Tue, 28 Sep 2021 15:17:06 +0200 Subject: [PATCH] Reduce allocations --- src/Julia/Problems001-050/Problem004.jl | 41 +++++++++++++++---------- 1 file changed, 25 insertions(+), 16 deletions(-) diff --git a/src/Julia/Problems001-050/Problem004.jl b/src/Julia/Problems001-050/Problem004.jl index aeba860..bbdb895 100644 --- a/src/Julia/Problems001-050/Problem004.jl +++ b/src/Julia/Problems001-050/Problem004.jl @@ -1,28 +1,37 @@ -#= +#= Created on 17 Jun 2021 @author: David Doblas Jiménez @email: daviddoji@pm.me Solution for Problem 4 of Project Euler -https://projecteuler.net/problem=4 -=# +https://projecteuler.net/problem=4 =# + +using BenchmarkTools +using Profile + +function ispalindrome(n::Int64) + # return digits(n) == reverse!(digits(n)) + for i in zip(digits(n), reverse!(digits(n))) + if i[1] ≠ i[end] + return false + end + end + return true +end function Problem4() - #= + #= A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. - Find the largest palindrome made from the product of two 3-digit numbers. - =# - ans = 0 - for i in 100:1000 - for j in 100:1000 - palindrome = i * j - s = string(palindrome) - if (s==reverse(s)) & (palindrome > ans) - ans = palindrome - end + Find the largest palindrome made from the product of two 3-digit numbers. =# + + ans = 10_001 + for i in 100:999, j in i:999 + num = i * j + if (num > ans) && ispalindrome(num) + ans = num end end @@ -31,6 +40,6 @@ end println("Time to evaluate Problem 4:") -@time Problem4() +@btime Problem4() println("") -println("Result for Problem 4: ", Problem4()) +println("Result for Problem 4: ", Problem4()) \ No newline at end of file