ปานกลาง 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก