Write A Program In Java BlueJ To print and check whether the numbers are Twin Prime or not , using function name as twin() . The Function returns 1 if they are Twin Prime otherwise it returns 0.
(Twin Prime Numbers are those which are primd and there difference is 2)
e.g :- (5,7) , (11,13) , etc.
Answers
Answer:
import java.util.Scanner;
public class TwinPrimes {
// Checking Prime number.
static boolean isPrime(int number) {
for (int i = 2; i < number; i++)
if (number % i = = 0)
return false;
return true;
}
// Checking Twin Prime numbers.
static int isTwinPrime(int numOne, int numTwo) {
// Finding their difference is 2 or not
if (Math.abs(numOne - numTwo) != 2)
return 0;
// Checking both numbers for Prime and returning values accordingly.
return (isPrime(numOne) && isPrime(numTwo)) ? 1 : 0;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter two numbers - ");
int numOne = sc.nextInt( ),
numTwo = sc.nextInt( );
System.out.printf("They are%sTwin Primes.", isTwinPrime(numOne, numTwo) = = 1 ? " " : " not ");
}
}