Twin Prime Series - Coder's point

Saturday, March 16, 2019

Twin Prime Series

 //A twin prime is a prime number that is either 2 less or 2 more than another prime number—for example, either member of the twin prime pair (41, 43).  
 import java.util.*;  
 class twin_prime  
 {   
   boolean TPrime(int n)  
   {  
     int count=0;  
     for(int i=1; i<=n;i++)  
     {  
       if(n%i==0)  
       {  
         count++;  
       }  
     }  
     if(count==2)  
       return true;  
     else  
       return false;  
   }  
   public static void main()  
   {  
     twin_prime obj = new twin_prime();  
     Scanner in = new Scanner(System.in);  
     System.out.println("Enter the starting range");  
     int p=in.nextInt();  
     System.out.println("Enter the ending range");  
     int q=in.nextInt();  
     if(p>q)  
     {  
       System.out.println("Invalid range");  
     }  
     else  
     {  
       System.out.println("The twin prime series is");  
       for(int i=p;i<=(q-2);i++)  
       {  
         if(obj.TPrime(i)== true&& obj.TPrime(i+2)==true)   
         {  
           System.out.print("("+i+","+(i+2)+") ");  
         }  
       }  
     }  
   }  
 }  
OUTPUT:
Enter the starting range
1
Enter the ending range
100
The twin prime series is
(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73) 

No comments:

Post a Comment