From dbe3f062ad66e1d8d05a3e7cb21a4a1b8165b181 Mon Sep 17 00:00:00 2001 From: Sanders Lin <45224617+SandersLin@users.noreply.github.com> Date: Sun, 10 Feb 2019 02:00:05 +0800 Subject: [PATCH] Project Euler Problem 14 Solution 2 (#651) --- project_euler/problem_14/sol2.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 project_euler/problem_14/sol2.py diff --git a/project_euler/problem_14/sol2.py b/project_euler/problem_14/sol2.py new file mode 100644 index 000000000000..b9de42be1108 --- /dev/null +++ b/project_euler/problem_14/sol2.py @@ -0,0 +1,16 @@ +def collatz_sequence(n): + """Collatz conjecture: start with any positive integer n.Next termis obtained from the previous term as follows: + if the previous term is even, the next term is one half the previous term. + If the previous term is odd, the next term is 3 times the previous term plus 1. + The conjecture states the sequence will always reach 1 regaardess of starting n.""" + sequence = [n] + while n != 1: + if n % 2 == 0:# even + n //= 2 + else: + n = 3*n +1 + sequence.append(n) + return sequence + +answer = max([(len(collatz_sequence(i)), i) for i in range(1,1000000)]) +print("Longest Collatz sequence under one million is %d with length %d" % (answer[1],answer[0])) \ No newline at end of file