Home > Programming > Project euler 26: Reciprocal cycles

Project euler 26: Reciprocal cycles


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

1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.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.

Solution:

I solved this problem in a bruteforce manner. Divisor keeps incrementing from 2 to 1000.
We store the reminder instead of quotient in an array. When the same reminder repeats we know there is a recurring cycle. The maximum of that recurring cycle is the answer.

#include <iostream>

#include <stdio.h>

using namespace std;
int max(int a, int b)
{
    return (a > b) ? a: b;
}

int remArray[2000];
int divideByOne(long divisor)
{
    int term = 0;
    long mul = 1;
    for(int i = 0; i < 2000; i++)
        remArray[i] = 0;
    while (mul != 0 && term < 2000) {
        term++;
        mul *= 10;
        mul %= divisor;
        if (remArray[mul] != 0)
            break;
        remArray[mul] = term;
    }
    return term;
}


int main()
{
       int max_val = 0;
       for(int i = 2; i <= 1000; i++)
        max_val = max(max_val, divideByOne(i));
       cout<<max_val;
        return 0;
}


time ./a.exe
Answer: 983
real 0m0.087s
user 0m0.030s
sys 0m0.046s

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: