From f21d3a972dd6733e2421d1ee450b20ce90485b15 Mon Sep 17 00:00:00 2001 From: Praneeth Jain Date: Mon, 2 Oct 2023 18:33:11 +0530 Subject: [PATCH] Add solution to Project Euler Problem 014 (#186) * added project euler 14 * added to ProjectEuler.jl * add tests for project euler 14 * switch to Int64 * switch to Int64 in tests --- src/project_euler/ProjectEuler.jl | 2 ++ src/project_euler/problem_014.jl | 42 +++++++++++++++++++++++++++++++ test/project_euler.jl | 7 ++++++ 3 files changed, 51 insertions(+) create mode 100644 src/project_euler/problem_014.jl diff --git a/src/project_euler/ProjectEuler.jl b/src/project_euler/ProjectEuler.jl index d40fb799..62932fc5 100644 --- a/src/project_euler/ProjectEuler.jl +++ b/src/project_euler/ProjectEuler.jl @@ -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") @@ -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 diff --git a/src/project_euler/problem_014.jl b/src/project_euler/problem_014.jl new file mode 100644 index 00000000..f5e9edf7 --- /dev/null +++ b/src/project_euler/problem_014.jl @@ -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 diff --git a/test/project_euler.jl b/test/project_euler.jl index 0e8b36ed..632f257b 100644 --- a/test/project_euler.jl +++ b/test/project_euler.jl @@ -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