-
-
Notifications
You must be signed in to change notification settings - Fork 107
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
- Loading branch information
1 parent
ddff15a
commit f21d3a9
Showing
3 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters