Find the nearest next prime to a given integer:
for example: int n = 45, result = 47;
int n = 8, result = 11
int GetNearestNextPrime(int n)
{
int result = -1;
for (int I = n+1; I < INT_MAX; I++)
{
if (isPrime(i)){
result = I;
break;
}
}
return result;
}
bool isPrime(int n)
{
var primes = new List<int>();
for (int I = 2; I <= n; I++)
{
bool composite = false;
for (int k =0 ; k < primes.Count; k++)
{
if (I % primes[k] == 0){
composite = true;
break;
}
}
if (composite == false){
primes.Add(I);
}
}
return primes.Contains(n);
}
Another way is to use the sieve of Eratosthenes to filter out prime:
for example: int n = 45, result = 47;
int n = 8, result = 11
int GetNearestNextPrime(int n)
{
int result = -1;
for (int I = n+1; I < INT_MAX; I++)
{
if (isPrime(i)){
result = I;
break;
}
}
return result;
}
bool isPrime(int n)
{
var primes = new List<int>();
for (int I = 2; I <= n; I++)
{
bool composite = false;
for (int k =0 ; k < primes.Count; k++)
{
if (I % primes[k] == 0){
composite = true;
break;
}
}
if (composite == false){
primes.Add(I);
}
}
return primes.Contains(n);
}
Another way is to use the sieve of Eratosthenes to filter out prime:
This is a very simple way to filter out the prime numbers upto n.
for i ranging from 2 to square root of n:
for j ranging from multiples of i upto n
mark the number as not prime
those that remain unmarked are the primes.
int count = 0;
for (int i = 0; i < primes.Count; i++)
for (int j = 0; j <= i; j++)
if (primes[i] != primes[j] && primes.Contains(primes[i] + primes[j]) && primes[i] + primes[j] <= n)
{
Console.WriteLine("{0},{1}", primes[j], primes[i]);
count++;
}
Console.Write("Count={0}", count);
No comments:
Post a Comment