Java program for Brun’s Constant and Twin Prime number

Java program for Brun’s Constant and Twin Prime number

Java program for Brun’s Constant


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:
Booleans isPrime(int n) Checks whether n is prime or not
Void twinPrimesBrunConstant – Which checks twin prime and also calculate brun’s constant.


Solution
import java.util.Scanner;
/**
 * class BrunsConstant
 * Input 2 nos. and check whether they make up Brun’s Constant or not, Brun’s Constant is sum of
 * reciprocal of Twin Prime Nos. e.g (1/3) + (1/5) is a Brun’s Constant
 */
public class BrunsConstant
{
    static double sum=0.0;
    static int i, f;
    // Check the number prime or not
    public static boolean isPrime(int n)
    {
        f=1;
        for (i = 2 ; i < n ; i++)
        {
            if(n % i == 0)
            {
                f=0;
                break;
            }
        }
        if(f == 1)
            return true;
        else
            return false;

    }


    // Here checked the two number twin prime or not
    // and also calculate brun's constant.
    public static void twinPrimesBrunConstant(int number )
    {
        System.out.println("Twin prime");
        System.out.println("==========");
        for (int i = 2; i < number ; i++)
        {
            int num1 = i;
            int num2 = i + 2;
            if (isPrime(num1) && isPrime(num2))
            {
                System.out.println(num1 + " " + num2);
                sum = sum + (double)1/num1 + (double)1/num2;
            }
        }
    }

    public static void main(String[] args)
    {
        int no;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        no = scanner.nextInt();
        twinPrimesBrunConstant(no);
        System.out.println("Brun's Constant:" + sum);
    }
}

Advanced Java: Learn Java Advanced Features


Output
Enter a number: 13
Twin prime
==========
3 5
5 7
11 13
Brun's Constant:1.044022644022644
Enter a number: 50
Twin prime
==========
3 5
5 7
11 13
17 19
29 31
41 43
Brun's Constant:1.2698646333745234


More Program

Java program to check palindrome




SHARE THIS
Previous Post
Next Post