Euler Problem 125


Euler Problem 125:

Unutar minute:

class Program
{
    static void Main(string[] args)
    {
        int N = 100000000;
       // int N = 1000;
        List<long> nums= new List<long>();
        List<int> palindrom= new List<int>();
        for (int i = 2; i < N; i++)
            if (IsPalindrom(i.ToString()))
                palindrom.Add(i);

       for (int i = 0; i < palindrom.Count; i++)
        {
            int num=palindrom[i];
            if (IsSumSquare(num))
                nums.Add(num);

        }
       Console.WriteLine(nums.Sum());
       Console.WriteLine("Press any key to continue...");
       Console.Read();
    }

    private static bool IsSumSquare(int num)
    {
        int sqrt = (int)Math.Sqrt(num);
        if (sqrt * sqrt == num)
            sqrt -= 1;
        for (int j = sqrt; j >= 2; j--)
        {
            bool found = false;
            int k = j;
            int sum = 0;
            while (true)
            {
                sum += k * k;
                if (sum == num)
                  return true;
                else if (sum > num)
                    break;
                else if (k > 1)
                    k--;
                else
                    break;
            }
            if (found)
                break;

        }
        return false;
    }
     static bool IsPalindrom(string n)
    {
        int lnl;
        if (n.Length % 2 != 0)
            lnl = 1 + n.Length / 2;
        else
            lnl = n.Length / 2;

        int ln = n.Length;
        for (int i = 0; i < ln / 2; i++)
            if (n[i] != n[ln - 1 - i])
                return false;
        return true;
    }

}

About Bahrudin Hrnjica

PhD in Mechanical Engineering, Microsoft MVP for .NET. Likes .NET, Math, Mechanical Engineering, Evolutionary Algorithms, Blogging.

Posted on 19/03/2010, in Project Euler and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s