Saturday, December 19, 2009

Twin Prime Numbers

class TwinPrimes
{
public static void main(String[] args)
{
int LastPrime = 1;
for (int n = 0; n < 1000; n++)
{
if (isPrime(n)) // We only care about prime numbers
{
if ((n - LastPrime) == 2) // If the difference between this prime and the last prime is 2
{
System.out.println((n - 2) + " and " + n + " are twin primes"); // We have a twin prime
}
LastPrime = n; // Store the last prime so we can compare it to the next one
}
}
}

public static boolean isPrime(int n)
{
if (n <= 1) // Not prime
return false;
if (n == 2) // Prime
return true;
if (n % 2 == 0) // Divisible by 2 means it's always not a prime
return false;

// For all other numbers, test by checking the divisibility of the square root of the number
int m = (int)Math.round(Math.sqrt(n));

for (int i = 3; i <= m; i += 2)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
}

No comments:

Post a Comment