Monday 13 April 2009

PROJECT EULER #44

Link to Project Euler problem 44

Pentagonal numbers are generated by the formula, Pn=n(3n-1)/2. The first ten pentagonal numbers are:

1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...

It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 - 22 = 48, is not pentagonal.

Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference is pentagonal and D = |Pk - Pj| is minimised; what is the value of D?



using System;
using System.Collections.Generic;

namespace project_euler
{
class Program
{
static void Main()
{
//Problem 44
DateTime start = DateTime.Now;
int diff;
double n;
List<int> pent = new List<int>(10000);
for (int i = 0; i < 10000; i++)
{
//add pentagonals to list
pent.Add((i+1)*(3*(i+1) - 1)/2);
for (int j = 0; j < i; j++)
{
diff = pent[i] - pent[j];
//check if diff is pentagonal
n = (Math.Sqrt(24*diff + 1) + 1)/6;
//if n is an integer
if (n == Math.Floor(n))
{
n = (Math.Sqrt(24*(diff + pent[i]) + 1) + 1)/6;
if (n == Math.Floor(n))
Console.WriteLine(pent[j]);
}
}
}
TimeSpan time = DateTime.Now - start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
}
}

No comments: