SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

Twin Prime Numbers Program in Java and Python

02 November 2014

Twin prime numbers program with algorithm, explanation, Java solution and simple Python solution for ICSE and ISC students.

Question:

Write a program to print all the Twin Prime numbers within a given range.

Note: Twin Prime numbers are a pair of numbers which are both prime and whose difference is 2.

INPUT: Enter the lower range: 1 Enter the upper range: 100 OUTPUT: The Twin Prime Numbers within the given range are: (3, 5) (5, 7) (11, 13) (17, 19) (29, 31) (41, 43) (59, 61) (71, 73)

Algorithm:

Step 1: Start.

Step 2: Accept the lower range p and upper range q.

Step 3: If p > q, display invalid range and stop.

Step 4: Define a method isPrime(n) to test whether a number is prime.

Step 5: In isPrime(n), return false if n < 2.

Step 6: Run a loop from 2 to n / 2; if any number divides n, return false.

Step 7: If no divisor is found, return true.

Step 8: In the main program, run i from p to q - 2.

Step 9: For each i, check whether i and i + 2 are both prime.

Step 10: If both are prime, display the pair as twin primes.

Step 11: Continue until all possible pairs in the range have been tested.

Step 12: Stop.

Explanation:

The solution uses a helper method because the same prime-checking logic is needed for both numbers in a possible twin-prime pair. A number less than 2 is rejected immediately because it cannot be prime.

Inside isPrime(), the loop searches for a divisor. If any value divides the number exactly, the number has more than two factors and the method returns false. If the loop completes without finding a divisor, the number is prime.

The main loop checks every possible starting number i in the range. The second number in the pair is always i + 2, so the loop only needs to continue up to q - 2.

A pair is printed only when both calls, isPrime(i) and isPrime(i + 2), return true. This ensures that the difference condition and prime condition are both satisfied.

Twin primes are pairs of prime numbers that differ by 2. The program must therefore do two things: identify prime numbers and compare neighbouring candidates. A prime-checking method is used to test whether a number has exactly two factors or no divisors other than 1 and itself. Then for each number in the range, the program checks whether both the number and the number plus 2 are prime. This avoids storing all primes first and directly prints valid twin-prime pairs.

Java Program:

Java
/**
* The class TwinPrimeRange inputs 2 numbers and prints all the
* twin prime numbers within that range
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.util.Scanner;
class TwinPrimeRange
{
    boolean isPrime(int n) //funton for checking prime
    {
        int count=0;
        for(int i=1; i<=n; i++)
        {
            if(n%i == 0)
            count++;
        }
        if(count == 2)
        return true;
        else
        return false;
    }

    public static void main(String args[])
    {
        TwinPrimeRange ob = new TwinPrimeRange();
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the lower range : ");
        int p = sc.nextInt();
        System.out.print("Enter the upper range : ");
        int q = sc.nextInt();

        if(p>q)
        System.out.println("Invalid Range !");
        else
        {
            System.out.println("\nThe Twin Prime Numbers within the given range are : ");
            for(int i=p; i<=(q-2); i++)
            {
                if(ob.isPrime(i) == true && ob.isPrime(i+2) == true)
                {
                    System.out.print("("+i+","+(i+2)+") ");
                }
            }
        }
    }
}

Equivalent Python Program:

Python
def is_prime(n):
    if n < 2:
        return False

    # Search for a divisor from 2 up to half of the number.
    for i in range(2, n // 2 + 1):
        if n % i == 0:
            return False
    return True


p = int(input("Enter the lower range: "))
q = int(input("Enter the upper range: "))

# The lower limit must not be greater than the upper limit.
if p > q:
    print("Invalid Range")
else:
    print("The Twin Prime Numbers within the given range are:")

    # The second number of every twin-prime pair is i + 2.
    for i in range(p, q - 1):
        if is_prime(i) and is_prime(i + 2):
            print("(", i, ", ", i + 2, ")", sep="", end=" ")

Output:

Enter the lower range: 1 Enter the upper range: 200 The Twin Prime Numbers within the given range are: (3, 5) (5, 7) (11, 13) (17, 19) (29, 31) (41, 43) (59, 61) (71, 73) (101, 103) (107, 109) (137, 139) (149, 151) (179, 181) (191, 193) (197, 199)

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →