protected override void Solve(out string answer) { NumberDivisor numberDivisor = new NumberDivisor(); long n = 220; long f = numberDivisor.CalculateSumOfProperDivisors(n); Answer = f.ToString(); Dictionary <long, long> mapOfNumbersToDivisors = new Dictionary <long, long>(); // Identify the list of all d() functions under 10000. foreach (int number in Enumerable.Range(1, 10000)) { long dFunction = numberDivisor.CalculateSumOfProperDivisors(number); mapOfNumbersToDivisors.Add(number, dFunction); } //mapOfNumbersToDivisors.Add(220, d(220)); //mapOfNumbersToDivisors.Add(284, d(284)); List <long> amicableNumbers = new List <long>(); // Find the amicable numbers mapOfNumbersToDivisors.AsParallel().ForAll(mapEntry => { long key = mapEntry.Key; if (amicableNumbers.Contains(key)) { return; // Make sure we do not count the same amicable number twice. } long value = mapEntry.Value; try { long reverseKey = mapOfNumbersToDivisors[value]; if (key == reverseKey) //Key and value are the two amicable numbers. Add them to the list to remember. { if (key != value) //amicability requires that d(a) = b and d(b) = a, where a != b { amicableNumbers.Add(key); amicableNumbers.Add(value); } } } catch (KeyNotFoundException e) { //There is no reverse value in the collection, so no chance of amicability. string m = e.Message; } }); var sumOfAmicableNumbers = amicableNumbers.Sum(); answer = string.Format("The sum of all the amicable numbers under 10000 is {0}.", sumOfAmicableNumbers); }
public void TestPerfects() { DateTime start = DateTime.Now; long temp = 28; NumberDivisor numberDivisor = new NumberDivisor(); var sumDivisors = numberDivisor.CalculateSumOfProperDivisors(temp); var is28Abundant = numberDivisor.IsAbundantOrDeficientOrPerfect(temp); var is12Abundant = numberDivisor.IsAbundantOrDeficientOrPerfect(12); var is57Abundant = numberDivisor.IsAbundantOrDeficientOrPerfect(57); var elapsedTime = DateTime.Now - start; var sb = new StringBuilder(); sb.AppendFormat("Elapsed computation time: {0}. Sum of properDivisors of {1} = {2}.", elapsedTime, temp, sumDivisors); sb.AppendLine(); sb.AppendFormat("Number {0} is {1}.", temp, is28Abundant); sb.AppendLine(); sb.AppendFormat("Number {0} is {1}.", 12, is12Abundant); sb.AppendLine(); sb.AppendFormat("Number {0} is {1}.", 57, is57Abundant); sb.AppendLine(); Answer = sb.ToString(); }