ยาก 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Longest Recurring Cycle

Find the d up to a limit whose fraction 1/d has the longest repeating decimal block.

สิ่งที่คุณจะได้เรียนรู้

  • Simulate long division with remainders
  • Detect a repeat with a lookup table
  • Find a cycle length from first positions

โจทย์

ดูฉบับแปล

Some unit fractions end (1/4 = 0.25) and the rest repeat forever: 1/6 = 0.1666... repeats a block of 1 digit and 1/7 = 0.142857142857... a block of 6. Among d = 2, 3, ..., limit, find the d whose 1/d has the longest repeating block. Do the long division by hand in code: the digits start repeating as soon as a remainder comes back.

Implement longest_recurring_cycle(limit).

Input

limit: The largest denominator to try.

Output

Return the d with the longest repeating block. A fraction that ends has a block length of 0. If several d tie, return the smallest.

เงื่อนไข

2 ≤ limit ≤ 2000

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
limit = 8

ผลลัพธ์ที่คาดหวัง:
expected = 7
อินพุต:
long long limit = 8;

ผลลัพธ์ที่คาดหวัง:
long long expected = 7;
อินพุต:
long limit = 8;

ผลลัพธ์ที่คาดหวัง:
long expected = 7;

คำอธิบาย

Block lengths for 2 to 8 are 0, 1, 0, 0, 1, 6, 0, so the answer is 7.

ตัวอย่างที่ 2
อินพุต:
limit = 5

ผลลัพธ์ที่คาดหวัง:
expected = 3
อินพุต:
long long limit = 5;

ผลลัพธ์ที่คาดหวัง:
long long expected = 3;
อินพุต:
long limit = 5;

ผลลัพธ์ที่คาดหวัง:
long expected = 3;

คำอธิบาย

1/3 repeats one digit, 1/2, 1/4 and 1/5 end, so the answer is 3.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Each new digit of 1/d comes from the remainder times 10.

คำใบ้ 2

Remember the step where each remainder first appeared.

คำใบ้ 3

If the remainder becomes 0 the decimal ends; otherwise the cycle length is the gap between two visits of the same remainder.

ความซับซ้อนที่คาดหวัง

O(limit²) time, O(limit) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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

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

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