In this tutorial you will learn about the Program to check Twin prime In Java and its application with practical example.
In this tutorial, we will learn to create a Java Program to check Twin prime In Java using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Twin Prime Number.
A Number is called a Prime if it is Divisible by itself and Twin Prime number having a prime gap of two(2) is referred to as a twin prime number.
For Example:->
- 29 and 31 are Twin Prime Number.(31-29=2).
- 3 and 5 are Twin Prime Number.(5-3 =2).
- 71 and 73 are Twin Prime Number.(73-71 =2).
Program to check Twin prime In Java
In this program we would find given numbers are Twin prime number or not .first of we would take a value from user and find the Twin prime .let have a look at the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// JAVA Program for Twin prime number.. import java.util.*; import java.util.Scanner; class Twin { static boolean Prime(int number) { if (number <= 1) return false; if (number <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (number % 2 == 0 || number % 3 == 0) return false; for (int i = 5; i * i <= number; i = i + 6) if (number % i == 0 || number % (i + 2) == 0) return false; return true; } // Returns true if num and num1 are twin primes static boolean Twin_Prime(int num, int num1) { return (Prime(num) && Prime(num1) && Math.abs(num - num1) == 2); } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter first Prime number"); int no1 = in.nextInt(); Scanner in1 = new Scanner(System.in); System.out.println("Enter Second Prime number"); int no2 = in1.nextInt(); if (Twin_Prime(no1, no2)) System.out.println("Twin Prime"); else System.out.println("Not Twin Prime"); } } |
Output
Twin Prime number
Not a Twin Prime number.
In the above program, we have first declared and initialized a set variables required in the program.
- number = it will hold entered numbers
- num,num1,no1 and no2= it will hold entered numbers.
After that we take a number from user and find given number is a Twin Prime number or not.
After taking two prime number we pas this number to Prime() function where we calculate is there difference or prime number is 2 if yes.
Function returns true
else return False.