통계, IT, AI

26. Reciprocal cycles 본문

IT/PROJECT_EULER

26. Reciprocal cycles

Harold_Finch 2017. 1. 29. 12:23

1. 개요

문제는 이곳에서 확인할 수 있다. 1보다 크고 1000보다 작은 어떤 자연수 d로 순환소수 1/d를 만들 수 있다. 예를 들어 1/6=0.1(6)이며 1/7=0.(142857)이다. 순환되는 부분이 가장 긴 d를 찾는 것이 목표이다. 


2. 구현: ver 1.0

나눗셈을 수행하면서 순환되는 부분이 어디에서 발생하는지 확인한다.  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# -*- coding: utf-8 -*-
 
 
def count_reciprocal_cycles(d):
    """나눗셈을 수행하면서 나머지가 0이면 순환되는 부분이 없으므로 0을 반환한다.
       나머지가 이미 발생한 나머지라면 순환이 시작되는 부분이므로 이 부분을 찾는다."""
    quotient_list, remainder_list = [], []
    n = 1
 
    while True:
        quotient, remainder = divmod(n, d)
        quotient_list.append(quotient)
 
        if remainder == 0 or (remainder != 0 and remainder in remainder_list):
            break
 
        remainder_list.append(remainder)
        n = remainder * 10
 
    if remainder == 0:
        return 0
    else:
        return len(quotient_list) - remainder_list.index(remainder) - 1
 
longest_recurring_cycle = 0
for d in range(1, 1000):
    recurring_cycle = count_reciprocal_cycles(d)
 
    if longest_recurring_cycle < recurring_cycle:
        print('d: ', d)
        print('recurring cycle: ', recurring_cycle)
        longest_recurring_cycle = recurring_cycle

답은 983이다.

'IT > PROJECT_EULER' 카테고리의 다른 글

28. Number spiral diagonals  (0) 2017.01.30
27. Quadratic primes  (0) 2017.01.29
25. 1000-digit Fibonacci number  (0) 2017.01.28
24. Lexicographic permutations  (0) 2017.01.27
23. Non-abundant sums  (0) 2017.01.27
Comments