Skip to content

Instantly share code, notes, and snippets.

@fluttert

fluttert/Euler.cs Secret

Last active Aug 29, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.