모든 챌린지
어려움 1명 해결 정답률 100.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에 맞게 수정되었습니다. 위의 설명과 제약 조건을 기준으로 풀어 주세요.

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

# 코더 언어 시간 메모리 AI 평가 풀이
1 ННикита Python 1,004 ms - 5/5 코드 보기

다른 사람의 풀이 보기

커뮤니티 풀이

스포일러: 아래에 전체 풀이 1개가 있습니다 먼저 직접 풀어보세요. 다른 개발자의 코드와 AI 리뷰도 참고할 수 있습니다. 로그인하고 문제를 풀면 토론에 참여할 수 있습니다.