Author Topic: Java program to print twin prime numbers  (Read 6731 times)

kathir

  • Administrator
  • Sr. Member
  • *****
  • Posts: 283
Java program to print twin prime numbers
« on: November 28, 2011, 06:08:40 pm »
Here is the Java program to print the twin prime numbers under 1000. You can increase or decrease this limit by simply changing the value condition in the for loop.

Code: (Java)
//Source Code Listing

import java.lang.*;
import java.util.*;
import java.io.*;
 
 
class TwinPrime
{
      static boolean IsPrimeNumber(int num)
      {
         boolean bPrime = true;
         int factor = num / 2;

         int i = 0;

         for (i = 2; i <= factor; i++)
         {
            if ((num % i) == 0)
               bPrime = false;
         }
         return bPrime;
      }

 
      public static void main(String[] args)
      {
         int firstprime = 0, secondprime = 0, totalTwinPrimeNumbers = 0;

         System.out.println("List of Twin prime numbers under 1000");

         for (int i = 2; i <= 1000; i++)
         {
            if (IsPrimeNumber(i) == true)
            {
               if (firstprime == 0)
                  firstprime = i;
               else
                  secondprime = i;
               boolean IsTwinPrimeNumber = ((secondprime - firstprime) == 2);
               if (IsTwinPrimeNumber == true)
               {
                  System.out.format("%d, %d\n", firstprime, secondprime);
                  totalTwinPrimeNumbers++;
               }
               secondprime = firstprime = i;
            }
         }
         System.out.format("Total number of twin prime numbers under 1000: %d\n\n", totalTwinPrimeNumbers);   
      }
}


 


Disclaimer: This web site is for educational and informational purposes only. Click here to read the Disclaimer.
Content copyright 2010-2014. Kathiresan. All rights reserved.
This page is using SMF version 2.0.1