Sunday 12 April 2009

PROJECT EULER #38

Link to Project Euler problem 38

Take the number 192 and multiply it by each of 1, 2, and 3:

192 x 1 = 192
192 x 2 = 384
192 x 3 = 576

By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3)

The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).

What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1?


using System;
using System.Text;

namespace project_euler
{
class Program
{
static void Main()
{
//Problem 37
DateTime start = DateTime.Now;
string test = "123456789";
long max = 0;
for (int i = 1; i < 10000; i++)
{
StringBuilder sb = new StringBuilder();
for (int j = 1; j < 10; j++)
{
sb.Append(i*j);
if (sb.Length == 9)
{
string result = sb.ToString();
char[] c = result.ToCharArray();
Array.Sort(c);
string s = new string(c);
if (s == test)
max = int.Parse(result) > max
? int.Parse(result)
: max;
}
}
}
Console.WriteLine(max);
TimeSpan time = DateTime.Now - start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
}
}

No comments: