CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
namespace PrimeNumbers
{
public static class PrimeCheck
{
public static void Main()
{
SearchForPrimeNumbers(3, 1000);
}
public static void SearchForPrimeNumbers(long lowestNumberToCheck, long highestNumberToCheck)
{
const long LOWEST_PRIME_NUMBER = 2;
List<long> foundPrimes = new List<long>();
foundPrimes.Add(LOWEST_PRIME_NUMBER);
long numberToCheck = lowestNumberToCheck;
long latestPrimeNumber = foundPrimes.First();
Console.WriteLine("Searching for prime numbers between {0} and {1}", lowestNumberToCheck, highestNumberToCheck);
while (numberToCheck <= highestNumberToCheck)
{
if (IsPrimeNumber(foundPrimes, numberToCheck))
{
foundPrimes.Add(numberToCheck);
Console.WriteLine("Prime number: " + numberToCheck.ToString());
}
numberToCheck = numberToCheck + 2;
}
Console.WriteLine("Longest Prime: {0} - {1} digits", foundPrimes.Last(), foundPrimes.Last().ToString().Length);
}
private static bool IsPrimeNumber(List<long> foundPrimes, long numberToCheck)
{
bool isPrime = true;
foreach (long foundPrime in foundPrimes)
{
if (numberToCheck % foundPrime == 0)
{
isPrime = false;
break;
}
}
return isPrime;
}
}
}