Java program for Brun’s Constant and Twin Prime number

Twin Primes are the prime numbers with a difference of 2, e.g., (3, 5), (5, 7), (11, 13), (17, 19) … etc. The sum of reciprocals of the twin primes up to a limit, converges to sum known as Brun’s Constant.

Example : Say for Inputted number 13 and its twin primes are (3, 5), (5, 7), (11, 13) and its sum of reciprocals is (1/3 + 1/5) + (1/5 + 1/7) + (1/11 + 1/13) =  1.044022644022644

Write a program to create Primes which include methods:
boolean isPrime(int n) – Checks whether n is prime or not

And check twinPrime and also calculate Brun’s constant.

import java.util.Scanner;
class BrunsConstant
{
    static boolean isPrime(int n)
    {
        int c=0;
        for(int i=1; i<=n; i++)
        {
            if(n%i==0)
            c++;
        }
        if(c==2)
            return true;
        else
            return false;
    }
  
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number");
        int n = in.nextInt();
        double b=0;
        System.out.println("Twin Primes");
        for(int i=1; i<=n-2; i++)
        {
            //condition for twin prime
            if(isPrime(i)&&isPrime(i+2))
            {
                System.out.println(i + "\t" + (i+2));
                b += (double)1/i + (double)1/(i+2);
            }
        }
        System.out.println("Value of Brun's Constant upto " +n+ " is : " +b);
    }
}

Video Explanation

Leave a Comment

Your email address will not be published. Required fields are marked *