created by Aha00aAha00a at 2016-11-18
last modified by Aha00aAha00a at 2026-11-15
revision: 4

Project Euler Problem14

http://projecteuler.net/index.php?section=problems&id=14

Large sum

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.

다음의 반복되는 수열은 양수들의 집합으로 정의된다.

n → n/2 (n이 짝수일 때)

n → 3n + 1 (n이 홀수일 때)

위의 규칙을 이용하여, 13으로 부터 시작하면 다음과 같은 수열을 얻을 수 있다.

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

이 수열은 (13으로 시작해서 1로 끝나는) 10개의 수를 가진다. 비록 아직 증명은 되지 않았지만(콜라츠 추측), 모든 숫자는 1로 끝난다고 생각된다.

100만 미만에서 어떤 수가 가장 긴 체인을 생성하는가?

주의: 체인이 시작되면 포함되는 수는 100만을 넘어가도 됨

1. Solution

(837799,1,525)
new {
  @tailrec
  def collatz(start:Long, current: Long, termCount: Long = 1): (Long, Long) = {
    if (current == 1) {
      (start, termCount)
    } else if (current % 2 == 0) {
      collatz(start, current / 2, termCount + 1)
    } else {
      collatz(start, current * 3 + 1, termCount + 1)
    }
  }

  val ans = (1 to 1000000).map(i => collatz(i, i)).maxBy(_._2)
}.ans

-- 2016-11-18

2. See Also

2.2. Adjacent Pages

≤ 32
all
1.0x
1.0x
80
-120
ON
0/0
0/0
0.00
0
0 / 0
1.00x