http://projecteuler.net/problem=92
Problem 92
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- 89Therefore 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?
static void Main(string[] args) { DateTime dt1 = DateTime.Now; int count89 = 0; for (int j = 1; j < 10000000; j++) { double currentNum = j; while (true) { double returnedSum = getNextNum(currentNum); currentNum = returnedSum; if (returnedSum == 1) break; if (returnedSum == 89) { count89++; break; } } } Console.WriteLine("Chains that end in 89 : "+count89); DateTime dt2 = DateTime.Now; Console.WriteLine("time "+ (dt2-dt1)); } public static double getNextNum(double num) { double sum = 0; string currentNum = "" + num; for (int i = 0; i < currentNum.Length; i++) { double numSquare = int.Parse(currentNum[i].ToString()); sum += Math.Pow(numSquare, 2.00); } return sum; } |