Been on hols… so mini break from this.. but had the chance to do one more…
Here we need to find the sum of all products which use numbers 1-9 ONCE in being formed from 2 multipliers and the product itself…
e.g. 4 x 1738 = 6952 => uses 1,2,3,4,5,6,7,8,9
Note we should only include each product (eg 6952) once in the final sum… so I used a list for this.
Other tips – the product and multipliers can be formed into a string.. whose length must be 9.. anything else would mean a double or missing value.
Also we only need test up to 9876 (we could do 9999 but it’d be pointless as there are repeated values there already!)
_________________________
static void Main(string[] args)
{
BigInteger sum = 0;
List<long> found = new List<long>();
for (long a = 1; a < 9876; a++)
{
for (long b = 1; b < 9876; b++)
{
long c = a * b;
if (contains1to9once(a, b, c))
{
if (!found.Contains(c))
{
sum += c;
found.Add(c);
}
}
}
}
Console.WriteLine(sum);
Console.ReadLine();
}
static bool contains1to9once(long a, long b, long c)
{
string s = a.ToString() + b.ToString() + c.ToString();
//has to be 9 chars long only with one of each
if(s.Length==9 &&
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)
{
return true;
}
return false;
}
No comments:
Post a Comment