Algorithm, Data structure/Solved Algorithmic Problem

Project Euler #26 - Reciprocal cycles

JaykayChoi 2016. 5. 28. 11:00

A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:

1/20.5
1/30.(3)
1/40.25
1/50.2
1/60.1(6)
1/70.(142857)
1/80.125
1/90.(1)
1/100.1

Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.

Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.


출처: https://projecteuler.net/



숫자 6이 주어졌을 때 분모를 1로 할 경우 0.166666... 으로 표현할 수 있고 반복되는 숫자 6을 순환 마디라고 합니다. d를 1000 미만의 숫자라 할 때 순환마디가 가장 긴 숫자를 구하는 문제입니다.

naive하게 재귀함수로 1000 이하의 모든 수의 순환마디를 계산하여 풀었습니다. memoization 을 이용해서 시간 복잡도를 줄이는 최적화를 할 수 있지 않을까 생각이 듭니다. 



my solving 

c++

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
 
using namespace std;
 
int maxDenominator;
 
int recursive(int i, int value, int count)
{
    if (value == || count > maxDenominator)
        return count;
 
    value *= 10;
    value %= i;
    count++;
    recursive(i, value, count);
}
 
int solve()
{
    int curMaxCount = 0;
    int ret = 0;
 
    for (int i = 2; i <= maxDenominator; i++)
    {
        int count = 0;
        int value = 10 % i;
 
        count = recursive(i, value, count);
 
        if (count > curMaxCount && count <= maxDenominator)
        {
            curMaxCount = count;
            ret = i;
        }
    }
 
    return ret;
}
 
int main() 
{
    maxDenominator = 1000;
 
    cout << solve() << endl;
 
    system("pause");
    return 0;
}
cs


'Algorithm, Data structure > Solved Algorithmic Problem' 카테고리의 다른 글

USACO 1.1 - Friday the Thirteenth  (0) 2016.05.29
USACO 1.1 - Greedy Gift Givers  (0) 2016.05.29
USACO 1.1 - Your Ride Is Here  (0) 2016.05.27
UVa - Ecological Bin Packing  (0) 2016.05.27
UVa -Train Swapping  (0) 2016.05.25