Truncatable primes: Difference between revisions
Content deleted Content added
→{{header|C}}: Adding C# |
|||
Line 143:
739399
Press Enter</pre>
=={{header|C sharp|C#}}==
<lang csharp>using System;
using System.Diagnostics;
namespace RosettaCode
{
internal class Program
{
public static bool IsPrime(int n)
{
if (n<2) return false;
if (n<4) return true;
if (n%2==0) return false;
if (n<9) return true;
if (n%3==0) return false;
var r = (int) Math.Sqrt(n);
var f = 6-1;
while (f<=r)
{
if (n%f==0 ||n%(f+2)==0)
return false;
f += 6;
}
return true;
}
private static bool IsRightTruncatable(int n)
{
for (;;)
{
n /= 10;
if (n==0)
return true;
if (!IsPrime(n))
return false;
}
}
private static bool IsLeftTruncatable(int n)
{
string c = n.ToString();
if (c.Contains("0"))
return false;
for (int i = 1; i<c.Length; i++)
if (!IsPrime(Convert.ToInt32(c.Substring(i))))
return false;
return true;
}
private static void Main()
{
var sb = new Stopwatch();
sb.Start();
int lt = 0, rt = 0;
for (int i = 1000000; i>0; --i)
{
if (IsPrime(i))
{
if (rt==0 && IsRightTruncatable(i))
rt = i;
else if (lt==0 && IsLeftTruncatable(i))
lt = i;
if (lt!=0 && rt!=0)
break;
}
}
sb.Stop();
Console.WriteLine("Largest truncable left is={0} & right={1}, calculated in {2} msec.",
lt, rt, sb.ElapsedMilliseconds);
}
}
}</lang>
<pre>Largest truncable left is=998443 & right=739399, calculated in 16 msec.</pre>
=={{header|Clojure}}==
|