C#: Project Euler Solutions to Problems 21 and 52

http://projecteuler.net/problem=21

Evaluate the sum of all the amicable numbers under 10000.

int totalsum = 0;
for (int num = 1; num < 10000; num++)
{
    int tempsum = 0;
    for (int i = 1; i < num; i++)
    {
        if (num % i == 0)
            tempsum += i;
    }
    int secondtempsum = 0;
    for (int i = 1; i < tempsum; i++)
    {
        if (tempsum % i == 0)
            secondtempsum += i;
    }
    if (secondtempsum == num && num !=tempsum)
    {
        Console.WriteLine("amicable pair  " + num + " , " + tempsum );
        totalsum += num;
    }
}
Console.WriteLine(" Final sum : "+totalsum);

http://projecteuler.net/problem=52

It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.

Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.

static void Main(string[] args)
{
    long count = 1;
    while (true)
    {
        long initnum = count;
        long t2 = initnum * 2;
        long t3 = initnum * 3;
        long t4 = initnum * 4;
        long t5 = initnum * 5;
        long t6 = initnum * 6;
        if (compareNums(initnum, t2) && 
            compareNums(initnum, t3) && 
            compareNums(initnum, t4) && 
            compareNums(initnum, t5) && 
            compareNums(initnum, t6))
        {
            Console.WriteLine(initnum);
            break;
        }
        count++;
    }
}
 
public static bool compareNums(long a, long b)
{
    string initstring = "" + a;
    string doublestring = "" + b;
    bool found = false;
    foreach (char digit in doublestring)
    {
        foreach (char innerchar in initstring)
        {
            if (innerchar == digit)
                found = true;
        }
        if (!found)
            return false;
        found = false;
    }
    return true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *