-
-
Save fluttert/a79f75a1c0249286cf2b to your computer and use it in GitHub Desktop.
Euler 44
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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