Project Euler Problem #71!

July 7th, 2010
by Serinox

I’m just getting back into the swing of things here after a busy period between work, life and college.

Anyways, Problem #71 says:

Consider the fraction, n/d, where n and d are positive integers. If n

If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get:

1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8

It can be seen that 2/5 is the fraction immediately to the left of 3/7.

By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7.


So the trick here is to just look at the denominators. We know the number we are trying to get close to is 3/7 so we make the numerator ((3/7)*denominator) which will most likely be a float, we then take the floor of that value which gives us the closest integer and use that value as the numerator. We then check the numerator and denominator against each other to make sure the GCD is 1. We can then check to see if this new fraction is closer to (3/7) or further away than the last value we checked keeping the closer of the two.

Solution runs in around 2 seconds. Written in c#/mono.

using System;
using System.Collections;
using System.Diagnostics;

namespace Problem71
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			Fraction Standard = new Fraction(3,7);
			Fraction Closest = new Fraction(0,1);
			Stopwatch sw = new Stopwatch();
			sw.Start();

			for (int d = 1; d<=1000000;d++)
			{
				int n = (int)Math.Floor(((double)3/(double)7)*d);
					if (GCD(d,n) == 1)
					{
						Fraction f = new Fraction(n,d);
						if (f.Value < Standard.Value)
						{
							if (f.Value > Closest.Value)
							{
								Closest = f;
							}
						}

					}

			}
			sw.Stop();
			Console.Write(Closest.Numerator.ToString() + "/" +
                             Closest.Denominator.ToString()+System.Environment.NewLine);
			Console.WriteLine(sw.Elapsed);
			Console.ReadLine();
		}
		public static int GCD (int a, int b)
		{
			if (b == 0)
				return a;
			else
				return GCD(b,(a%b));
		}
	}
	class Fraction
	{
		public Fraction (int n, int d)
		{
			_numerator = n;
			_denominator = d;
		}
		private int _numerator;
		private int _denominator;
		public int Numerator
		{
			get{return _numerator;}
			set{_numerator = value;}
		}
		public int Denominator
		{
			get{return _denominator;}
			set{_denominator = value;}
		}
		public decimal Value
		{
			get{return (((decimal)_numerator)/((decimal)_denominator));}
		}
	}
}

Tags:
Posted in Project Euler | Comments (0)

No comments yet

Leave a Reply

You must be logged in to post a comment.