Last one for today… this isn’t fast code but works…
A bit of a speed up implemented by only checking those which are of length equal to their max character… so there’s not point checking 17 as it’s 2 in length.. so max permitted would be 12… however 132 is fine as it’s 3 in length and has a 3 in it!
_______________________
static void Main(string[] args)
{
long max=0;
for (long i = 1; i < 987654321; i++)
{
int len = i.ToString().Length;
//find max char
int maxchar = 0;
foreach (char c in i.ToString())
{
if (c - 48 > maxchar)
{
maxchar = c - 48;
}
}
//only check if this could be pandigital - by checking max char and len
//eg1 17 can't be pandigital as only 2 chars long (eg2 12 =OK, 13=not)
string s = i.ToString();
if (maxchar == len && isprime(i))
{
if (s.Split('1').Length==2 && s.Split('2').Length==2 )
{
if (i.ToString().Length==2 && i > max) {max=i;}
if (s.Split('3').Length==2)
{
if (i.ToString().Length==3 && i > max) {max=i;}
if (s.Split('4').Length==2)
{
if (i.ToString().Length==4 && i > max) {max=i;}
if (s.Split('5').Length==2)
{
if (i.ToString().Length==5 && i > max) {max=i;}
if (s.Split('6').Length==2)
{
if (i.ToString().Length==6 && i > max) {max=i;}
if (s.Split('7').Length==2)
{
if (i.ToString().Length==7 && i > max) {max=i;}
if (s.Split('8').Length == 2)
{
if (i.ToString().Length == 8 && i > max) { max = i; }
if (s.Split('9').Length == 2)
{
if (i.ToString().Length == 9 && i > max) { max = i; }
break;
}
}
}
}
}
}
}
}
}
}
Console.WriteLine(max);
Console.ReadLine();
}
static bool isprime(long n)
{
if (n == 2 || n == 3 || n == 5) { return true; }
if (n%2==0) {return false;}
if (n%3 == 0) { return false;}
if (n%5 == 0) { return false;}
for (int t = 7; t < Math.Sqrt(n); t++)
{
if (n % t== 0)
{
return false;
}
}
return true;
}
No comments:
Post a Comment