C#: Project Euler Solutions to Problems 12 and 41

I have completed 25 Project Euler Questions without cheating. I was awarded a badge that looks like this.

http://projecteuler.net/problem=12

What is the value of the first triangle number to have over five hundred divisors?

int max = 0;
int n = 1;
while(true)
{
    double value = (.5 * n) * (n + 1);
    int devisor_count = 0;
    for (int i = 1; i <= value; i++)
    {
        if (value % i == 0)
            devisor_count++;
    }
    if (max < devisor_count)
    {
        max = devisor_count;
        Console.WriteLine(n + " value  " + value + " devisor Count :" + devisor_count);
    }
    if (devisor_count > 500)
    {
        Console.WriteLine(n + " value  " + value + " FINAL  devisor Count :" + devisor_count);
        break;
    }
    n++;
}

http://projecteuler.net/problem=41

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

static void Main(string[] args)
{
    int n = 1;
    while (true)
    {
        if (isPrime(n))
        {
            if (Order(n))
                Console.WriteLine(n);
        }
        n++;
    }
}
 
public static bool Order(int n)
{
    string mynum = ""+n;
    int [] int_array = new int[mynum.Length];
    for (int i = 0; i < mynum.Length; i++)
        int_array[i] = int.Parse(mynum[i].ToString());
    Array.Sort(int_array);
    if (int_array[0] == 1)
    {
        int count = 2;
        for (int j = 1; j < int_array.Length; j++)
        {
            if (count == int_array[j])
                count++;
            else 
                return false; 
        }
    }
    else
        return false;
    return true;
}
 
public static bool isPrime(int n)
{
    if (n == 1)
        return false;
    if (n == 2)
        return true;
    for (int i = 2; i < n; ++i)
    {
        if ((n % i) == 0)
            return false;
    }
    return true;
}

Leave a Reply

Your email address will not be published.