Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Project_Euler_Problem_21
- {
- class Program
- {
- static void Main()
- {
- // Accept only valid input!
- int input = 0;
- do
- {
- Console.Write("Max Value: ");
- } while (!int.TryParse(Console.ReadLine(), out input));
- Program MainProgram = new Program();
- // Execute the program!
- int sum = MainProgram.FindAmicableSum(input);
- // Result.
- Console.WriteLine("\nSum of Amicable Numbers: {0}", sum);
- Console.ReadLine();
- }
- public int FindAmicableSum(int maxValue)
- {
- // Heavy lifting all starts here.
- Number[] numberArray = new Number[maxValue + 1];
- // Create numbers.
- for (int i = 0; i <= maxValue; i++)
- {
- numberArray[i] = new Number(i);
- }
- // Selects only amicable numbers.
- return numberArray.Select(x => x.Amicable == true ? x.Value : 0).Sum();
- }
- }
- public class Number
- {
- // Contains information about each individual number.
- public Number(int value)
- {
- // All information about the number is determined internally while being constructed.
- this.Value = value;
- DivisorSum = FindDivisorSum(value);
- TestAmicablity();
- }
- public readonly int Value;
- public int DivisorSum { get; private set; }
- public bool Amicable { get; set; }
- private static int FindDivisorSum(int n)
- {
- // Just an intermediate step between finding the divisor and returning the sum. Refactor all the things!
- List<int> divisorList = FindDivisors(n);
- return divisorList.Sum();
- }
- private static List<int> FindDivisors(int n)
- {
- // A linear search is performed. Could be more efficient if I used O(n/m) complexity.
- List<int> divisorList = new List<int>();
- for (int i = 1; i < n; i++)
- {
- if (n % i == 0)
- {
- divisorList.Add(i);
- }
- }
- return divisorList;
- }
- private void TestAmicablity()
- {
- // Test amicability, pretty simple stuff.
- Amicable = (Value == FindDivisorSum(DivisorSum) && Value != DivisorSum);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement