Friday, December 13, 2013

Problem 71 - Processing

I decided to solve problem 71 in Processing. Now, Processing is, like ChucK, not a language that was designed for Project Euler, it is a language designed for drawing things and other things that involve graphics. Nonetheless, it worked fairly well for the purposes of this problem. The main trick was counting down from 1000000 to circumvent precision problems.
int gcd(int a, int b) {
  if (b == 0) {
    return a;
  } else {
    return gcd(b, a%b);
  }
}

void draw() {
  int closest = 0;
  double smallestDiff = 10;
  for (int d = 1000000; d > 8; --d) {
      int num = floor(3.0 / 7.0 * d);
      double diff = (3.0/7.0) - (num*1.0) / d;
      if (diff < smallestDiff && num / gcd(num, d) != 3) {
        smallestDiff = diff;
        closest = num / gcd(num, d);
      }
  }
  println(closest);
  noLoop();
}

No comments:

Post a Comment