RitinMalhotra

Twin Primes in a Range

Oct 29th, 2018
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. /**
  2. * This program inputs 2 numbers and prints all the twin prime numbers within that range.
  3. */
  4. import java.util.Scanner;
  5. public class TwinPrimes
  6. {
  7.     public static boolean isPrime(int num) //Function to check whether a number is a prime number or not.
  8.     {
  9.         if(num == 2) //Since 2 is the first prime number.
  10.         {
  11.             return true;
  12.         }
  13.         else
  14.         {
  15.         int i, flag=1;
  16.         for(i=2;i<num;i++)
  17.         {
  18.             if(num%i==0)
  19.             {
  20.                 flag=0;
  21.                 break;
  22.             }
  23.         }
  24.         if(flag == 1)
  25.         {
  26.             return true;
  27.         }
  28.         else
  29.         {
  30.             return false;
  31.         }
  32.         }
  33.     }
  34.     public static void twinPrimes(int start, int end) //Function to find twin primes in a range.
  35.     {
  36.         int i;
  37.         boolean c1,c2;
  38.         System.out.println("Twin Primes between "+start+" and "+end+" are:");
  39.         for(i=start+1;i<end-1;i++)
  40.         {
  41.             c1=isPrime(i); //Checking whether a number is prime or not.
  42.             if(c1==true)
  43.             {
  44.                 c2=isPrime(i+2); //If the number above is a prime, we will check whether (number + 2) is a prime as well or not.
  45.                 if(c2==true) //A pair of twin primes is found!
  46.                 {
  47.                     System.out.println("( "+i+","+(i+2)+" )");
  48.                 }
  49.             }
  50.         }
  51.     }
  52.     public static void main(String args[])
  53.     {
  54.         Scanner sc=new Scanner(System.in);
  55.         System.out.println("Please enter the lower limit: ");
  56.         int start=sc.nextInt();
  57.         System.out.println("Please enter the upper limit: ");
  58.         int end=sc.nextInt();
  59.         if(start > end) //Checking whether the user is an idiot or not.
  60.         {
  61.             System.out.println("Incorrect Input. The lower limit must be lesser than the upper limit.");
  62.         }
  63.         else
  64.         {
  65.             twinPrimes(start,end);
  66.         }
  67.         sc.close();
  68.     }
  69. }
Add Comment
Please, Sign In to add comment