모든 챌린지
보통 0명 해결 정답률 0%

Longest Collatz Chain

Find the starting number up to a limit whose Collatz chain is longest.

배우게 될 내용

  • Generate a Collatz chain
  • Cache results to avoid repeated work
  • Break ties by the smallest value

문제

번역본 보기

From any positive n, the Collatz rule makes the next term n / 2 when n is even and 3n + 1 when n is odd, and the chain stops when it reaches 1. The chain for 6 is 6, 3, 10, 5, 16, 8, 4, 2, 1: nine terms. Among all starting numbers from 1 to limit, find the one with the most terms.

Implement longest_collatz_chain(limit).

Chains share their endings, so remembering the length found for each number saves a lot of work. Terms along the way can pass the limit; use 64-bit integers.

Input

limit: The largest starting number to try.

Output

Return the starting number whose chain has the most terms (counting the start and the final 1). If several tie, return the smallest of them.

제약 조건

1 ≤ limit ≤ 100,000

예시

예시 1
입력:
limit = 6

예상 출력:
expected = 6
입력:
long long limit = 6;

예상 출력:
long long expected = 6;
입력:
long limit = 6;

예상 출력:
long expected = 6;

설명

The chain lengths for 1 to 6 are 1, 2, 8, 3, 6 and 9 terms, so the answer is 6.

예시 2
입력:
limit = 10

예상 출력:
expected = 9
입력:
long long limit = 10;

예상 출력:
long long expected = 9;
입력:
long limit = 10;

예상 출력:
long expected = 9;

설명

9 gives 20 terms (9, 28, 14, 7, ...), more than any other start up to 10, so the answer is 9.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

Count the terms of one chain first, including the start and the 1.

힌트 2

When a chain reaches a number whose length you already know, add instead of continuing.

힌트 3

Only replace the best start when a length is strictly greater.

예상 복잡도

O(limit × average new steps) time, O(limit) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

아직 통과한 풀이가 없습니다. 풀어서 1위를 차지하세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.