Tuesday, April 3, 2012

Program to print 'n' twin Prime numbers


import java.util.Scanner;
public class TwinPrime {
   
    public static void main(String a[])
    {

         System.out.println("This program prints 1st n twin prime nummbers");
        Scanner sc= new Scanner(System.in);
        int input = sc.nextInt();
        int i=3,n=35;
        boolean k,task=true;
             
            int count =0;
             while(task)
              {
                     if((isPrime(i)) & ( isPrime(i+2)))
                     {  
                         count++;
                         System.out.println("  "+(i-2)+"  "+i );
                         if(count==input ) { task = false; }
                     }
                     i+=2;
              }
            

 System.out.println("Total no of twin prime Numbers:-"+count );

   
    }
    public static boolean isPrime(int n) {

    //check if n is a multiple of 2
    if (n%2==0) return false;

    //if not, then just check the odds
    for(int i=3;i*i<=n;i+=2) {
        if(n%i==0)
            return false;
    }
    return true;
}

}

No comments:

Post a Comment