Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This program inputs 2 numbers and prints all the twin prime numbers within that range.
- */
- import java.util.Scanner;
- public class TwinPrimes
- {
- public static boolean isPrime(int num) //Function to check whether a number is a prime number or not.
- {
- if(num == 2) //Since 2 is the first prime number.
- {
- return true;
- }
- else
- {
- int i, flag=1;
- for(i=2;i<num;i++)
- {
- if(num%i==0)
- {
- flag=0;
- break;
- }
- }
- if(flag == 1)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- public static void twinPrimes(int start, int end) //Function to find twin primes in a range.
- {
- int i;
- boolean c1,c2;
- System.out.println("Twin Primes between "+start+" and "+end+" are:");
- for(i=start+1;i<end-1;i++)
- {
- c1=isPrime(i); //Checking whether a number is prime or not.
- if(c1==true)
- {
- c2=isPrime(i+2); //If the number above is a prime, we will check whether (number + 2) is a prime as well or not.
- if(c2==true) //A pair of twin primes is found!
- {
- System.out.println("( "+i+","+(i+2)+" )");
- }
- }
- }
- }
- public static void main(String args[])
- {
- Scanner sc=new Scanner(System.in);
- System.out.println("Please enter the lower limit: ");
- int start=sc.nextInt();
- System.out.println("Please enter the upper limit: ");
- int end=sc.nextInt();
- if(start > end) //Checking whether the user is an idiot or not.
- {
- System.out.println("Incorrect Input. The lower limit must be lesser than the upper limit.");
- }
- else
- {
- twinPrimes(start,end);
- }
- sc.close();
- }
- }
Add Comment
Please, Sign In to add comment