Skip to content

Commit

Permalink
Add solution to Project Euler Problem 014 (#186)
Browse files Browse the repository at this point in the history
* added project euler 14

* added to ProjectEuler.jl

* add tests for project euler 14

* switch to Int64

* switch to Int64 in tests
  • Loading branch information
PraneethJain authored Oct 2, 2023
1 parent ddff15a commit f21d3a9
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/project_euler/ProjectEuler.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export problem_010
export problem_011
export problem_012
export problem_013
export problem_014

include("../math/divisors.jl")
include("../math/sieve_of_eratosthenes.jl")
Expand All @@ -34,5 +35,6 @@ include("problem_010.jl")
include("problem_011.jl")
include("problem_012.jl")
include("problem_013.jl")
include("problem_014.jl")

end
42 changes: 42 additions & 0 deletions src/project_euler/problem_014.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""
Longest Collatz Sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n+1 (n is odd)
Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
# Input parameters:
- `n` : upper bound on the starting number
# Examples/Tests:
```julia
problem_014(10) # returns 9
problem_014(250) # returns 231
problem_014(1000000) # returns 837799
problem_014(-1) # throws DomainError
```
# Reference
- https://projecteuler.net/problem=14
Contributed by: [Praneeth Jain](https://www.github.com/PraneethJain)
"""
function problem_014(n::Int64)
n < 1 && throw(DomainError("n must be a natural number"))
return argmax(collatz_length, 1:n)
end

cache = Dict{Int64,Int64}(1 => 1)
function collatz_length(x::Int64)
# If result already in cache, then return it
haskey(cache, x) && return cache[x]

# Recursively call the function and update the cache
return cache[x] = if x % 2 == 0
1 + collatz_length(x ÷ 2)
else
2 + collatz_length((3x + 1) ÷ 2)
end
end
7 changes: 7 additions & 0 deletions test/project_euler.jl
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,11 @@ using TheAlgorithms.ProjectEuler
@testset "Project Euler: Problem 013" begin
@test problem_013() == "5537376230"
end

@testset "Project Euler: Problem 014" begin
@test problem_014(Int64(10)) == 9
@test problem_014(Int64(250)) == 231
@test problem_014(Int64(1000000)) == 837799
@test_throws DomainError problem_014(Int64(-1))
end
end

0 comments on commit f21d3a9

Please sign in to comment.