KnowledgeBoat Logo

Computer Applications

Write a program to input two numbers and check whether they are twin prime numbers or not.
Hint: Twin prime numbers are the prime numbers whose difference is 2.
For example: (5,7), (11,13), ……. and so on.

Java

Java Nested for Loops

83 Likes

Answer

import java.util.Scanner;

public class KboatTwinPrime
{
    public void twinPrimeCheck() {

        Scanner in = new Scanner(System.in);

        System.out.print("Enter first number: ");
        int a = in.nextInt();

        System.out.print("Enter second number: ");
        int b = in.nextInt();

        boolean isAPrime = true;

        for (int i = 2; i <= a / 2; i++) {

            if (a % i == 0) {
                isAPrime = false;
                break;
            }

        }

        if (isAPrime && Math.abs(a - b) == 2) {
            
            boolean isBPrime = true;
            
            for (int i = 2; i <= b / 2; i++) {

                if (b % i == 0) {
                    isBPrime = false;
                    break;
                }
                
            }
            
            if (isBPrime)
                System.out.println(a + " and " + b + " are twin prime");
            else
                System.out.println(a + " and " + b + " are not twin prime");
        }
        else
            System.out.println(a + " and " + b + " are not twin prime");
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program to input two numbers and check whether they are twin prime numbers or not. Hint: Twin prime numbers are the prime numbers whose difference is 2. For example: (5,7), (11,13), ……. and so on.

Answered By

21 Likes


Related Questions