Find Twin Primes
Find the first 1000 twin prime numbers in Java using an isPrime function for the primality check and a value comparison between the prime numbers.
|
On Thursday, October 2nd 2008 at 04:00 AM By Andrew Pociu (View Profile)
    (Rated 0 with 0 votes) |
Contextual Ads
More Java Resources
Advertisement
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
for (int i = 3; i <= m; i += 2)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
}
|
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
|
Rate this code snippet
Current Comments
There are no comments.
|
Related Source Code
There is no related code.
Related Tutorials
There are no related tutorials.
Java Job Search
|