Project Euler Problem #119!

August 9th, 2011
by Serinox

Problem #119 is looking for:

The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 83 = 512. Another example of a number with this property is 614656 = 284.

We shall define an to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum.

You are given that a2 = 512 and a10 = 614656.

Find a30.

This is another problem on Project Euler that is much easier if you turn it inside out. The problem wants you to calculate the digit sum \(dsum\) of a number \(n\) and do something like \(log_{dsum}(n) = exp \) then check to see that \(dsum^{exp} == n\) which is doable but really slow. The faster method is to loop through two sets of numbers \(dbase\) and \(dexp\) a base and an exponent and find the digit sum of the resulting number and compare it to the base or something like \(DigitSum(dbase^{dexp}) == dbase\). This second method is much faster.

Solution written in c#/mono and uses the big integer library System.Numerics so requires .Net 4 . Calculates a bunch of extra numbers because of the loose boundaries but still runs in less than 4 seconds.

using System;
using System.Numerics;
using System.Collections.Generic;

namespace Problem119
{
	class MainClass
	{
		public static void Main (string[] args)
		{

			List<BigInteger> An = new List<BigInteger>();
			int Max = 30;
			for (BigInteger dbase = 2; dbase <= 500;dbase++)
			{
				for (int dexp = 2; dexp <= 50;dexp++)
				{
					BigInteger n = BigInteger.Pow(dbase,dexp);
					if (n.ToString().Length == 1)
						continue;
					if (DigitalSum(n) == dbase)
					{
						if (!An.Contains(n))
						{
							An.Add(n);

						}
					}
				}
			}
			An.Sort();
			Console.WriteLine(An[Max-1]);
		}

		public static BigInteger DigitalSum (BigInteger i)
		{
			BigInteger digits = (BigInteger) i;
			BigInteger digitsum = 0;
			while (digits != BigInteger.Zero)
			{
				BigInteger temp = (BigInteger)(digits%10);
				digitsum += temp;
				digits = (digits -temp) / 10;
			}

			return digitsum;
		}
	}
}

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

No comments yet

Leave a Reply

You must be logged in to post a comment.