Improve performance
This commit is contained in:
parent
f5152ece96
commit
735795e9af
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user