Project Euler Problem #145!

December 1st, 2009
by Serinox

Problem #145 says:

Some positive integers n have the property that the sum [ n + reverse(n) ] consists entirely of odd (decimal) digits. For instance, 36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers reversible; so 36, 63, 409, and 904 are reversible. Leading zeroes are not allowed in either n or reverse(n).

There are 120 reversible numbers below one-thousand.

How many reversible numbers are there below one-billion (10^(9))?

The solution below is c# with .Net 4.0. It does a very basic divide and conquer on the one billion numbers to check. This will take a while to run depending on your computer, it ran reasonably fast on a quad core machine. Pretty simple stuff could be made much faster but was written out of boredom.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Parallel;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Net4Test
{
    class Program
    {
        static object LockHandle = new object();
        static long Answer = 0;
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            Parallel.For(1L, 1000000000L, i =>
                {
                    if (i % 50000 == 0)
                        Console.WriteLine(i);

                    if (Reversable(i))
                    {
                        lock (LockHandle)
                        {
                            Answer += 1;
                        }
                    }

                });

            Console.WriteLine(Answer);
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.ReadLine();
        }
        static bool Reversable(long l)
        {
            bool RetValue = true;
            char[] lchar = l.ToString().ToCharArray();
            Array.Reverse(lchar);

            if (lchar[0] != '0')
            {

                long Reversel = (long)Convert.ToDouble(new string(lchar));

                char[] AChar = (l + Reversel).ToString().ToCharArray();

                foreach (char c in AChar)
                {
                    if (!IsOdd(Convert.ToInt32(c.ToString())))
                        RetValue = false;
                }
            }
            else
                RetValue = false;
            return RetValue;
        }
        static bool IsOdd(int i)
        {
            if (i == 0)
                return false;
            if (i % 2 == 0)
                return false;
            else
                return true;
        }
    }
}

Tags: , , ,
Posted in Project Euler | Comments (0)

No comments yet

Leave a Reply

You must be logged in to post a comment.