이경수 선생님의 수학실험실

Problem 14(Longest Collatz sequence) 본문

Project Euler

Problem 14(Longest Collatz sequence)

(이경수) 2019. 2. 10. 18:05

Problem 14(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)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. 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?

NOTE: Once the chain starts the terms are allowed to go above one million.



In Python:

#PE14 Longest Collatz sequence
import time

start_time = time.time()
lenChain=[]

for num in range(2, pow(10, 6)):
i = 0
while num > 1:
i += 1
if num % 2 == 0:
num /= 2
else:
num = 3 * num + 1
lenChain.append(i)

print(lenChain.index(max(lenChain))+2)
print(time.time() - start_time, "seconds")

Run Time: 44.05256390571594 seconds



In Java:


//Euler14 Longest Collatz sequence

package project_euler;


public class Euler14 {

public static void main(String[] args) {

long startTime = System.currentTimeMillis();

int count = 0;

int maxCount = 0;

int maxValue = 0;

long num = 0;

for (int i = 2; i < Math.pow(10, 6); i++) {

num = i;

count = 0;

while (num > 1) {

if (num % 2 == 0) {

num /= 2;

}

else {

num = 3 * num + 1;

}

count++;

}

if (count > maxCount) {

maxCount = count;

maxValue = i;

}

}

System.out.println(maxValue);

long endTime = System.currentTimeMillis();

System.out.println((double)(endTime - startTime)/(double)1000 + "seconds");

}

}


Run time: 0.459seconds



Solution: 837799


[from Project Euler: https://projecteuler.net/problem=14]




'Project Euler' 카테고리의 다른 글

problem16 (Power digit sum)  (0) 2019.02.14
Problem 15(Lattice paths)  (0) 2019.02.11
Problem 13(Large sum)  (0) 2019.02.10
Problem 12(Highly divisible triangular number)  (0) 2019.02.10
Problem 11(Largest product in a grid)  (0) 2019.02.10
Comments