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
|
https://projecteuler.net/problem=14
|
||||||
=#
|
=#
|
||||||
|
|
||||||
function chain_length(n, terms)
|
function chain_length(n)#, terms)
|
||||||
length = 0
|
length = 0
|
||||||
while n != 1
|
while n > 1
|
||||||
if haskey(terms, n)
|
n = iseven(n) ? n >> 1 : 3n + 1
|
||||||
length += terms[n]
|
|
||||||
break
|
|
||||||
end
|
|
||||||
if n % 2 == 0
|
|
||||||
n = n ÷ 2
|
|
||||||
else
|
|
||||||
n = 3n + 1
|
|
||||||
end
|
|
||||||
length += 1
|
length += 1
|
||||||
end
|
end
|
||||||
return length
|
return length
|
||||||
@ -50,12 +42,10 @@ function Problem14()
|
|||||||
ans = 0
|
ans = 0
|
||||||
limit = 1_000_000
|
limit = 1_000_000
|
||||||
score = 0
|
score = 0
|
||||||
terms = Dict{Int, Int}()
|
for i in 1:2:limit # no need to check even numbers
|
||||||
sizehint!(terms, limit)
|
longest = chain_length(i)
|
||||||
for i in 1:limit
|
if longest > score
|
||||||
terms[i] = chain_length(i, terms)
|
score = longest
|
||||||
if terms[i] > score
|
|
||||||
score = terms[i]
|
|
||||||
ans = i
|
ans = i
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
Loading…
x
Reference in New Issue
Block a user