Search This Blog

Wednesday, December 15, 2010

Euler Problem 21

http://projecteuler.net/index.php?section=problems&id=21

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

___________________

static void Main(string[] args)
    {
        long sumofallpairs = 0;

        for (int n = 1; n < 10000; n++)
        {
            if (isamicablepair(n))
            {
                sumofallpairs +=n;
            }

        }

        Console.WriteLine(sumofallpairs);

 
    Console.ReadLine();

    }


    static bool isamicablepair (int n)
{
    int sum1 = 0;
    int sum2 = 0;

    foreach (int i in divisors(n))
    {
        sum1 += i;
    }

    foreach (int i in divisors(sum1))
    {
        sum2 += i;
    }

    if (n == sum2 && n != sum1)
    {
        return true;
    }
    else
    {
        return false;
    }

}

    static List<int> divisors(int n)
    {
        List<int> div = new List<int>();
        for (int d = 1; d < n; d++)
        {
            if (n % d == 0) { div.Add(d); }
        }

        return div;

    }

No comments: