Search This Blog

Wednesday, December 29, 2010

Euler Problem 38

So here you need to do some pandigital checks again like problem 32…

We know the answer must be bigger than that given in the example.. as I tried putting their example answer in to see if it was the answer they were after.. but no…! Anyway this means the final value is somewhere between 91873654 and 987654321… so that’s a start.

I was thinking the number of parts to split up the 9 digit number into may be 2,3,4.. as in 123,456789 would be 2 parts.. but to be a correct value then part 1 x 2 should equal part 2… (not here obviously as 123 * 2 = 246)…

My plan was to try this with 2 parts.. and if it didn’t work then look at 3 parts.. and so on.. but I ran it with 2 parts and got the answer so didn’t need to go any further than this!!

Not the smartest, or most elegant solution… but it did the job..

____________________

static void Main(string[] args)
{
//must be bigger than 918273654 as it's mentioned in question
//and I tested it as the answer and it wasn't..
for (int i = 987654321; i > 918273645; i--)
{
string s = i.ToString();

//contains 1-9 once - pandigital 9
if (
s.Split('1').Length == 2 &&
s.Split('2').Length == 2 &&
s.Split('3').Length == 2 &&
s.Split('4').Length == 2 &&
s.Split('5').Length == 2 &&
s.Split('6').Length == 2 &&
s.Split('7').Length == 2 &&
s.Split('8').Length == 2 &&
s.Split('9').Length == 2)
{

//check case of 2 parts
for (int n=1;n<9;n++)
{
int part1 = Convert.ToInt32(i.ToString().Substring(0,n));
int part2= Convert.ToInt32(i.ToString().Substring(n,i.ToString().Length-n));

if (part2==part1*2)
{
Console.WriteLine(i);
goto foo;
}

}

}//end of pandigital check
}


foo:
Console.WriteLine("Done!");
Console.ReadLine();

}

No comments: