project-euler

https://projecteuler.net/
Log | Files | Refs | README

Euler_71.cpp (1580B)


      1 #include "Euler.h"
      2 
      3 int Euler::OrderedFractions()
      4 {
      5     //I did this problem by with pen + paper, but here was my thought process.
      6     //For me, this was the most obvious starting point for denominator d <= 1,000,000
      7 
      8     EulerUtility::gcd(299999, 700000); //gcd = 7
      9 
     10     //Ok, they aren't relatively prime; Divide them down.
     11 
     12     EulerUtility::gcd(42857, 100000);
     13 
     14     //At this point I noticed that this numerator was similar to the repeating decimal of 3/7 (0.(428571)*...).
     15     //I remembered that you can represent a repeating pattern as a fraction by taking the sequence and dividing it by nines
     16     //luckily the sequence allows for d <=1,000,000 (though in hindsight, the problem was most likely designed with
     17     //this property in mind).
     18 
     19     EulerUtility::gcd(428571, 999999); //equal to 3/7
     20 
     21     EulerUtility::gcd(428570, 999999); //Removed 1, noticed that gcd = 1. Therefore relatively prime, and since there is
     22                                        //no value of d larger except 1,000,000 itself (which seems very unlikely) then
     23                                        //it is probably the answer. If it wasn't, then it would narrow the answer down to
     24                                        //d = 1,000,000 which would be trivial to work out from there.
     25 
     26     int xmax = 0, xmaxd = 2;
     27 
     28     for (int d = 2; d <= 1000000; ++d)
     29     {
     30         int x = 3 * d / 7;
     31 
     32         if ((d % 7) == 0)
     33         {
     34             --x;
     35         }
     36         if (x * xmaxd > xmax * d)
     37         {
     38             xmax = x, xmaxd = d;
     39         }
     40     }
     41 
     42     return xmax; //As it happens, it was correct.
     43 }