Project Euler Problem #92!

November 19th, 2009
by Serinox

Problem #92 says:

       A number chain is created by continuously adding
       the square of the digits in a number to form a new
number until it has been seen before.
For example,
44 → 32 → 13 → 10 → 1 → 1
85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89
Therefore any chain that arrives at 1 or 89 will become
stuck in an endless loop. What is most amazing is that
EVERY starting number will eventually arrive at 1 or 89.
How many starting numbers below ten million will arrive at 89?

This is pretty simple. Start a chain and see if it hits one of the two terminating conditions given. So a little recursive function, and maybe some .net 4.0 goodness to go though the ten million numbers efficiently. The below solution runs in less than a minute. It could be made more efficient by creating a list of numbers that we know terminate in 89 so when we run the function we can see if we’ve already checked that part of the chain. but its fast enough. Solution provided below REQUIRES the .Net 4.0 frame work!

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 Count = 0;
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            Parallel.For(1, 10000000, i =>
                {
                    CheckNumber(i);
                });

            Console.WriteLine(Count);
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.ReadLine();
        }
        static void CheckNumber(int i)
        {
            if (i == 1)
                return;
            if (i == 89)
            {
                Increment();
                return;
            }
            int c = 0;

            char[] nums = i.ToString().ToCharArray();
            foreach (char s in nums)
            {
                c += Convert.ToInt32(s.ToString()) * Convert.ToInt32(s.ToString());
            }

            CheckNumber(c);
        }
        static void Increment()
        {
            lock (LockHandle)
            {
                Count++;
            }
        }
    }
}

Posted in Project Euler | Comments (0)

No comments yet

Leave a Reply

You must be logged in to post a comment.