Project Euler #21: Amicable numbers

  • + 0 comments

    // C# using System; using System.Collections.Generic;

    class Program { static int S(int n) { int sum = 1;

        for (int x = 2; x <= Math.Sqrt(n); x++)
        {
            if (n % x == 0)
            {
                sum += x + n / x;
            }
        }
    
        return sum;
    }
    
    static void Main()
    {
        int numTestCases = int.Parse(Console.ReadLine());
        List<int> testCases = new List<int>();
    
        for (int i = 0; i < numTestCases; i++)
        {
            testCases.Add(int.Parse(Console.ReadLine()));
        }
    
        HashSet<int> result = new HashSet<int>();
    
        for (int x = 0; x <= testCases.Max(); x++)
        {
            if (x == S(S(x)) && x != S(x))
            {
                result.Add(x);
            }
        }
    
        foreach (int testCase in testCases)
        {
            Console.WriteLine(result.Where(x => x <= testCase).Sum());
        }
    }
    

    }