This is a program to calculate the largest prime number. Are there any possible improvements in style/speed/accuracy?
public static int? LargestPrime(int max)
{
if (max < 0)
return null;
int largestPrime = 0;
for (int i = 0; i <= max; i++)
{
bool? isPrime = IsPrime(i);
if ((bool)isPrime)
largestPrime = i;
if (i % 100000 == 0)
Console.WriteLine(largestPrime.ToString("N0"));
}
return largestPrime;
}
private static List<int> listPrimes = new List<int>() { 2, 3 };
private static int listPrimeMax;
private static int listPrimesCount = 100000;
private static bool firstA = true;
private static bool firstB = true;
public static bool? IsPrime(int n)
{
if (listPrimes.Count < listPrimesCount)
{
// from wiki
// function is_prime(n : integer)
// if n ≤ 1
// return false
// else if n ≤ 3
// return true
// else if n mod 2 = 0 or n mod 3 = 0
// return false
// let i ← 5
// while i×i ≤ n
// if n mod i = 0 or n mod(i + 2) = 0
// return false
// i ← i + 6
//return true
if (n < 0)
return null;
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i*i <= n; i += 6)
{
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
if (listPrimes.Count < listPrimesCount)
{
listPrimes.Add(n);
listPrimeMax = n;
}
return true;
}
else
{
if(firstA)
{
Console.WriteLine("in listPrimes");
firstA = false;
}
foreach (int i in listPrimes)
{
if (n % i == 0)
return false;
if (i * i > n)
break;
}
for (int i = listPrimeMax + 2; i*i <= n; i += 2)
{
if (n % i == 0)
return false;
}
if (listPrimes.Count < 100 * listPrimesCount)
{
listPrimes.Add(n);
listPrimeMax = n;
}
else if(firstB)
{
Console.WriteLine("in 100*listPrimes");
firstB = false;
}
return true;
}
}