Skip to content

Instantly share code, notes, and snippets.

@fluttert
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fluttert/a79f75a1c0249286cf2b to your computer and use it in GitHub Desktop.
Save fluttert/a79f75a1c0249286cf2b to your computer and use it in GitHub Desktop.
Euler 44
namespace Euler_solutions{
internal class Program{
private static void Main(string[] args)
{
Stopwatch sw = new Stopwatch(); sw.Start(); // for timing
long answer = 0;
// Double Dictionary for checking pentagonals and the values
Dictionary<long, long> pentagonals = new Dictionary<long, long>();
Dictionary<long, long> pentagonalsVals = new Dictionary<long, long>();
long i = 1;
while (true)
{ // determine current pentagonal number, and add these to both dictionaries
long curPentagonal = i * (3 * i - 1) / 2;
pentagonals.Add(i, curPentagonal);
pentagonalsVals.Add(curPentagonal, i);
for (long k = 1; k < i; k++)
{ // Pj + Pk = Pi; Subtracting Pi with Pk gives Pj
long PjVal = curPentagonal - pentagonals[k];
if (pentagonalsVals.ContainsKey(PjVal) // SUM = OK
&& pentagonalsVals.ContainsKey(pentagonals[k] - PjVal)) // DIFF = OK
{ // PjVal is a pentagonal number; and the difference is also pentagonal
answer = pentagonals[k] - PjVal;
Console.WriteLine("Pj=" + pentagonalsVals[PjVal] + ", Pk=" + k + ", Psum=" + i + ", Pdiff=" + pentagonalsVals[pentagonals[k] - PjVal]);
// ouput should be: Pj=1020, Pk=2167, Psum=2395, Pdiff=1912
break;
}
}
if (answer != 0) { break; } // answer = found
i++;
}
sw.Stop();
Console.WriteLine("Answer: " + answer); // Answer Euler 44: 5482660 , runs in 126 ms
Console.WriteLine("Runtime in miliseconds: " + sw.ElapsedMilliseconds);
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment