diff --git a/src/Julia/Problem014.jl b/src/Julia/Problem014.jl index 22d2e89..cc9f6a5 100644 --- a/src/Julia/Problem014.jl +++ b/src/Julia/Problem014.jl @@ -8,18 +8,10 @@ Solution for Problem 14 of Project Euler https://projecteuler.net/problem=14 =# -function chain_length(n, terms) +function chain_length(n)#, terms) length = 0 - while n != 1 - if haskey(terms, n) - length += terms[n] - break - end - if n % 2 == 0 - n = n รท 2 - else - n = 3n + 1 - end + while n > 1 + n = iseven(n) ? n >> 1 : 3n + 1 length += 1 end return length @@ -50,12 +42,10 @@ function Problem14() ans = 0 limit = 1_000_000 score = 0 - terms = Dict{Int, Int}() - sizehint!(terms, limit) - for i in 1:limit - terms[i] = chain_length(i, terms) - if terms[i] > score - score = terms[i] + for i in 1:2:limit # no need to check even numbers + longest = chain_length(i) + if longest > score + score = longest ans = i end end