Skip to content

Commit 14f538a

Browse files
committed
Feat: Project Euler Problem 14
1 parent e2f6bd9 commit 14f538a

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

DIRECTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,8 @@
153153
* [Sol2](https://github.com/TheAlgorithms/Ruby/blob/master/project_euler/problem_004/sol2.rb)
154154
* Problem 005
155155
* [Sol1](https://github.com/TheAlgorithms/Ruby/blob/master/project_euler/problem_005/sol1.rb)
156+
* Problem 014
157+
* [Sol1](https://github.com/TheAlgorithms/Ruby/blob/master/project_euler/problem_014/sol1.rb)
156158
* Problem 020
157159
* [Sol1](https://github.com/TheAlgorithms/Ruby/blob/master/project_euler/problem_020/sol1.rb)
158160
* Problem 021

project_euler/problem_014/sol1.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#Problem 14: https://projecteuler.net/problem=14
2+
3+
#Problem Statement:
4+
#The following iterative sequence is defined for the set of positive integers:
5+
#
6+
# n → n/2 (n is even)
7+
# n → 3n + 1 (n is odd)
8+
#
9+
#Using the rule above and starting with 13, we generate the following sequence:
10+
#
11+
# 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
12+
#
13+
#It can be seen that this sequence (starting at 13 and finishing at 1) contains
14+
#10 terms. Although it has not been proved yet (Collatz Problem), it is thought
15+
#that all starting numbers finish at 1.
16+
17+
#Which starting number, under one million, produces the longest chain?
18+
19+
def solution?()
20+
index_best_result = 0
21+
for num in 2..1000000
22+
index_candidate = 0
23+
n = num
24+
while n > 1
25+
if n%2 == 0
26+
n = n / 2
27+
else
28+
n = (3*n) + 1
29+
end
30+
index_candidate +=1
31+
end
32+
if index_best_result < index_candidate
33+
index_best_result = index_candidate
34+
value = num
35+
end
36+
end
37+
result = value
38+
end
39+
40+
answer = solution?()
41+
p answer
42+

0 commit comments

Comments
 (0)