Wednesday, 29 October 2014

Problem 26 Project Euler

Q]
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.

Solution:

main()
{
    int max=0;
int val=0;
int q=1;
int i=0;
int j;
int a[2000];
for(j=999;j>950;j--)
{
    q=1;
    for(i=0;i<2000;i++)
    {
        a[i]=0;
    }
    i=0;
while(q)
{
    //q*10/j is the expression for value after decimal point&& q changes from 1 initially to q*10%j
a[i]=(q*10)/j;
q=(q*10)%j;
i++;
if(i==1999){break;}
}
if(i==1999)//We will continue only if 1/d is recurring
{
    //to find max
for(i=0;i<2000;i++)
{
    int p=max;
    int y;
    for(y=i+1;y<2000;y++)
    {
        if(a[i]==a[y])
        {
            int mk;
            for(mk=i;mk<y;mk++)
            {
                if(a[mk]!=a[y+mk-i])
                {
                    break;
                }
            }
            if(mk==y)
            {
                if(max<y-i)
                {
                    max=y-i;
                    val=j;
                }
            break;
            }
        }
    }
if(p!=max){break;}
}
}
}
printf("%d",val);
}
//ANSWER=983

No comments:

Post a Comment