मध्यम 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 के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

हर कोडर का सबसे अच्छा पास हुआ समाधान। तेज़, कम मेमोरी वाले और बेहतर रेटिंग वाले समाधान ऊपर रहते हैं।

अभी कोई पास हुआ समाधान नहीं है। इसे हल करें और पहला स्थान पाएँ।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।