Tutte le sfide
Media 0 risolte 0% di accettazione

Longest Collatz Chain

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

1 ≤ limit ≤ 100,000

Esempi

Esempio 1
Input:
limit = 6

Output atteso:
expected = 6
Input:
long long limit = 6;

Output atteso:
long long expected = 6;
Input:
long limit = 6;

Output atteso:
long expected = 6;

Spiegazione

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

Esempio 2
Input:
limit = 10

Output atteso:
expected = 9
Input:
long long limit = 10;

Output atteso:
long long expected = 9;
Input:
long limit = 10;

Output atteso:
long expected = 9;

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.