Geekpedia Programming Tutorials






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
  1. class TwinPrimes
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 int LastPrime = 1;
  6.                 for (int n = 0; n < 1000; n++)
  7.                 {
  8.                         if (isPrime(n)) // We only care about prime numbers
  9.                         {
  10.                                 if ((n - LastPrime) == 2) // If the difference between this prime and the last prime is 2
  11.                                 {
  12.                                         System.out.println((n - 2) + " and " + n + " are twin primes"); // We have a twin prime
  13.                                 }
  14.                                 LastPrime = n; // Store the last prime so we can compare it to the next one
  15.                         }
  16.                 }
  17.         }
  18.  
  19.         public static boolean isPrime(int n)
  20.         {
  21.                 if (n <= 1) // Not prime
  22.                         return false;
  23.                 if (n == 2) // Prime
  24.                         return true;
  25.                 if (n % 2 == 0) // Divisible by 2 means it's always not a prime
  26.                         return false;
  27.                
  28.                 // For all other numbers, test by checking the divisibility of the square root of the number
  29.                 int m = (int)Math.round(Math.sqrt(n));
  30.  
  31.                 for (int i = 3; i <= m; i += 2)
  32.                 {
  33.                         if (n % i == 0)
  34.                         {
  35.                                 return false;
  36.                         }
  37.                 }
  38.                 return true;
  39.         }
  40. }
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this code snippet
Comment Current Comments
There are no comments.

Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Source Code
There is no related code.

Comment Related Tutorials
There are no related tutorials.

Jobs Java Job Search
My skills include:

Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons