Java program to print Twin Prime Numbers

Java program to print Twin Prime Numbers

Java program to print Twin Prime Numbers

Write a program in java to enter two numbers and check if they are twin prime numbers or not.

Twin Primes are the prime numbers with a difference of 2, e.g., (3, 5), (5, 7), (11, 13), (17, 19), (29, 31) ... etc. 

In this program isPrime(int n) will return true if the number is prime and false if it is not prime. This method is called in the main() method which checks the numbers are prime or not and also the difference between two prime numbers is 2. And if it is then it called Twin prime number.


Solution
import java.io.*;
// Program to check twin prime
public class TwinPrimeNumber
{
 
        public static boolean isPrime(int n)
        {
            // boolean value will return
            boolean f = true;

            for (int i = 2; i <= n / 2; i++) {
                if (n % i == 0) {
                    f = false;
                    break;
                }
            }

            return f;
        }

        // main method begins
        public static void main(String args[]) throws IOException
        {

            int number1, number2;
            // InputStreamReader object
            InputStreamReader in = new InputStreamReader(System.in);
            // BufferedReader object
            BufferedReader br = new BufferedReader(in);    
            System.out.print("Enter first number: ");
            // First number
            number1 = Integer.parseInt(br.readLine());
            System.out.print("Enter second number: ");
            // Second number
            number2 = Integer.parseInt(br.readLine());

            // Checking both the number is prime and the difference between two is 2
            if (isPrime(number1) == true && isPrime(number2) == true && Math.abs(number2 - number1) == 2) {
                System.out.println("Twin prime number");
            } else {
                System.out.println("Not twin prime numbers");
            }

        } // end method main
    } // end class



Output
Enter first number: 11
Enter second number: 13
Twin prime number

Enter first number: 9
Enter second number: 11
Not twin prime numbers

In the above program, a method public static boolean isPrime(int n) is used to check prime numbers. This method return a boolean value. If the number is prime then it will send true otherwise false. In main() method isPrime called two times to check true or false. 

//Twin prime number without method

import java.util.*;
public class TwinPrime
{
    public static void main(String args[])
    {
        int n1, n2, i, f1,f2;
        f1=f2=1;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter First number:");
        n1=sc.nextInt();
        System.out.println("Enter Second number:");
        n2=sc.nextInt();
        for(i=2; i<n1; i++)
        {
            if(n1%i==0)
            {
                f1=0;
                break;
            }
        }
        for(i=2; i<n2; i++)
        {
            if(n2%i==0)
            {
                f2=0;
                break;
            }
        }
        if(f1==1 && f2==1 && Math.abs(n1-n2)==2)
        {
            System.out.println("Twin Prime Number");
        }
        else
        {
            System.out.println("Not a Twin Prime Number");
        }
    }
}

More Program







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 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



Java program to check palindrome

Java program to check palindrome

Java program to check palindrome

Palindrome Number in Java


A Palindrome number or word which will read the same from either side, backward or forward.
For example, 202 or madam read the same from both forward and backward.

Java Program for Palindrome Number

import java.io.*;
public class PalindromeNumber
{
    public static void main(String args[])throws IOException
    {
        int n, rev, a ,m;
        rev=0;         
        InputStreamReader ab = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(ab);
        System.out.print("Enter number to Palindrome:");
        n = Integer.parseInt(br.readLine());
        m = n;
        // Reversing the number
        while(n != 0)
        {
            a = n % 10;
            rev = rev * 10 + a;
            n = n / 10;
        }
        System.out.println("Reverse Number:" + rev);
        // Checking Palindrome or not
        if(m == rev)
        {
            System.out.println("Palindrome");
        }
        else
        {
            System.out.println("Not Palindrome");
        }
    }
}

Output
Enter number to Palindrome:202
Reverse Number:202
Palindrome

Enter number to Palindrome:221
Reverse Number:122
Not Palindrome

Java Program for Palindrome Word or String

For String Palindrome
import java.util.Scanner;
/**
 * class Palindrome Word here.
 * Khurshid Md Anwar (InspireSkills)
 */
public class PalindromeWord
{
   public static void main(String args[])
   {
       Scanner sc = new Scanner(System.in);
       String st; // Variable for Word taken
       System.out.println("Enter a string or word ");
       st=sc.nextLine();
       int i,l;
       char ch;
       String revWord="";  // for reverse Word
       l = st.length();    // Finding the length of word
       for(i=0;i<l;i++)
       {
           ch = st.charAt(i);
           revWord = ch + revWord;
        }
         // Checking Plaindrome or not
        if(st.equals(revWord))
        {
            System.out.println("Palindrome Word");
        }
        else
        {
            System.out.println("Not a Palindrome Word");
        }       
    }
}

Output
Enter a string or word
madam
Palindrome Word
Enter a string or word
hello


Not a Palindrome Word

Visit for More Program

java program for isbn number




Addition of two matrices in Java

Addition of two matrices in Java

Addition of two matrices in Java


Java matrix addition


In this program, we are performing the addition of two matrices. Here we define two matrix one is first[][]
and another is second[][] and another one defines for summation of two entered matrices. First, we take row and column and then enter the values in two matrices. After then we sum the two matrices.



import java.util.Scanner;
/**
 * Java program for
 * Addition Of Two Matrices
  */
public class AdditionOfTwoMatrices
{
    public static void main(String args[])
    {
        int m, n, i, j;        // Local Variables
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number of rows and columns of matrix");
        m = sc.nextInt();
        n  = sc.nextInt();
        // Array definition 
        int first[][] = new int[m][n];       // First Array
        int second[][] = new int[m][n]; // Second Array
        int add[][] = new int[m][n];       // sum of two matrix array

        System.out.println("Enter the elements of first matrix");

        for (  i = 0 ; i < m ; i++ )
        {
            for ( j = 0 ; j < n ; j++ )
            {
                first[i][j] = sc.nextInt();
            }
        }

        System.out.println("Enter the elements of second matrix");

        for (  i = 0 ; i < m ; i++ )
        {
            for ( j = 0 ; j < n ; j++ )
            {
                second[i][j] = sc.nextInt();
            }
        }

        // Display of First Matrix
        System.out.println("Output of First Matrix");
        for (  i = 0 ; i < m ; i++ )
        {
            for ( j = 0 ; j < n ; j++ )
            {
                System.out.print(first[i][j] + " ");
            }
            System.out.println();
        }

        // Display of Second Matrix
        System.out.println("Output of Second Matrix");
        for (  i = 0 ; i < m ; i++ )
        {
            for ( j = 0 ; j < n ; j++ )
            {
                System.out.print(second[i][j] + " ");
            }
            System.out.println();
        }

        // Addition of matrix
        for (  i = 0 ; i < m ; i++ )
        {
            for ( j = 0 ; j < n ; j++ )
            {
                add[i][j] = first[i][j] + second[i][j];
            }
        }
       // Display of Matrix addition
        System.out.println("Addition of Two Matrix");

        for (  i = 0 ; i < m ; i++ )
        {
            for ( j = 0 ; j < n ; j++ )
            {
                System.out.print(add[i][j]+"\t");
            }
            System.out.println();
        }
    }
}


Output

Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
7
8
9
4
Enter the elements of second matrix
5
6
1
2
Output of First Matrix
7 8 
9 4 
Output of Second Matrix
5 6 
1 2 
Addition of Two Matrix
12 14
10 6

Visit for more programs


Array in Java

Array in Java

Array in Java


Array in Java

What is an Array?

The contiguous memory location is called Array. Actually, an array is a plural, so that we can simply read the variable and recognize that it is a collection of data. It is an object in Java that holds a fixed number of values of a single data type. Java Array is a data structure in java that can hold one or more values in a single variable. An array is declared like a variable except that we are attaching the square brackets [], which can be used in two parts, either before the name of the variable or after the name of the variable.

Why do we need an array?

Suppose you want to store the name of 500 employees, so we need to define 500 variables but this could be a very big problem so we need a better solution for defining 500 names for employees, that is why need an array.


Java array index starts at 0.
Array

Write down some points on Array.

  • The array is a homogeneous data structure that stores elements of a similar type.
  • All the elements of an array share the same name.
  • Each element of an array is treated separately and store in a different memory location.
  • Each value stored, in an array, is known as an element and all elements are indexed. The first element added, by default, gets 0 indexes. That is, the 6th element added gets an index number of 5.
  • Java checks the boundary array. If the index goes beyond, an exception will generate.
  • Elements of an array can be retrieved by their index number.
  • Java arrays are objects. With methods, the array elements can be manipulated.
  • Memory allocation in Java arrays are dynamically by using the new operator.
  • Arrays can be multidimensional.
  • Once the size of an array is defined, it cannot grow it or shrink it at run time. 


Declaring an Array

Int number [];
The above statement just declares an array object, but it doesn’t have any elements. An array is a null object. It must be instantiated using the following statement:
Number=new int [10];
In Java, every object is instantiated using the ‘new’ keyword.

Initialization of one dimensional array

Int arr[] = {5, 6, 1, 9, 3};
Array arr[] contains five elements in it.
Types Of Array

Types of Array in java

There are two types of array.

  1. Single Dimensional Array: Int arr[]=new int[10];
  2. Multidimensional Array: Int arr[][]=new int[5][5];

Java Array Literals

Sometimes we need predefine values for the array, so Java gives us a better solution for that, so we can use an array literal. Here is how we cab defines an array literal:
int[] number = {5, 4, 8, 9, 12, 6};
or
int number[] = {1,2,3,4,5,7,8};
Here we don’t need a new operator for defining the array.
So here values that are stored inside the curly brackets are called an array literal.
For defining String array we can do so as follows
String name[] = {“Alam”, “Binny”, Rakesh”, “Salim”, “Sachin”};

Some examples:

Simple Array print

import java.io.*;
public class SimpleArrayPrint
{
    public static void main(String args[])throws IOException
    {
            InputStreamReader ab=new InputStreamReader (System.in);
            BufferedReader br=new BufferedReader (ab);
            int n[]=new int[10];
            int i;
            System.out.println ("Enter Five numbers:");
            for (i=0;i<5;i++)
            {
                                                                n[i]=Integer.parseInt(br.readLine());
                                                }
                                                System.out.println ("Out Put");
                                                for (i=0;i<5;i++)
                                                {
                                                                System.out.print (n[i]+" ");
                                                }
                }
}

Example
Array Summation print
import java.io.*;
public class SumArrayPrint
{
    public static void main(String args[])throws IOException
    {
            InputStreamReader ab=new InputStreamReader(System.in);
            BufferedReader br=new BufferedReader(ab);
            int n[]=new int[10];
            int i,s=0;
            System.out.println("Enter ten numbers:");
            for(i=0;i<10;i++)
            {
                                                                n[i]=Integer.parseInt(br.readLine());
                                                }
                                                System.out.println("Out Put");
                                                for(i=0;i<10;i++)
                                                {
                                                                s=s+n[i];
                                                }
                                                System.out.println("Sum="+s);
                }
}

Output

Enter ten numbers:
2
3
65
66
5
8
12
4
54
5
Out Put
Sum=224

Example

Array program of Odd and Even

import java.io.*;
public class ArrayOddEven
{
    public static void main(String args[])throws IOException
    {
            InputStreamReader ab=new InputStreamReader(System.in);
            BufferedReader br=new BufferedReader(ab);
            int a[]=new int[10];
            int ev[]=new int[10];
            int od[]=new int[10];
            int i,j,k;
            j=k=0;
            System.out.println("Enter Five elements:");
            for(i=0;i<10;i++)
            {
                a[i]=Integer.parseInt(br.readLine());
            }
            for(i=0;i<10;i++)
            {
                if(a[i]%2==0)
                {
                  ev[j]=a[i];
                  j++;
                }
                else
                {
                    od[k]=a[i];
                    k++;
                }
            }
            System.out.println("Even Array");
            for(i=0;i<j;i++)
            {
                System.out.println(ev[i]);
            }
            System.out.println("Odd Array");
            for(i=0;i<k;i++)
            {
                System.out.println(od[i]);
            }
    }
}
Output
Enter Five elements:
4
5
6
3
2
1
7
8
9
2
Even Array
4 6 2 8 2
Odd Array
5 3 1 7 9

Write a java program to print all the prime numbers from an array

import java.util.*;
public class Array1
{
    public static void main(String args[])
    {
        int n[]=new int[10];  //[9, 7, 6 ,5........]
        int i, f, j;  
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter number:");
        for(i=0; i<10; i++)
        {
            n[i]=sc.nextInt();
        }
        System.out.println("Output");
        for(i=0; i<10; i++)
        {
            f=1;
            // Prime number check
            for(j=2; j<n[i]; j++)
            {
                if(n[i] % j == 0)
                {
                    f=0;
                    break;
                }
            }
            if(f == 1)
            {
                System.out.println(n[i]);
            }
        }       
    }
}

Double Dimension Array Example

import java.io.*;
class DBLArray
{
public static void main(String arg[])throws IOException
{
int n[][]=new int[3][3];
int i,j;
InputStreamReader ab=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ab);
System.out.println("Enter Data :");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
n[i][j]=Integer.parseInt(br.readLine());
}
}
System.out.println("OutPut Data");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(n[i][j]+" ");
}
System.out.println("");
}
}
}

Java Array Exception example

public class ArrayException
{
    public static void main(String args[])
    {
        int n[]={5,6,7,8,9};
        int i,m;
        try
        {
            m=n[4];
            System.out.println(m);
        }
        catch(Exception e)
        {
            System.out.println("O no not again");
        }
        finally
        {
            System.out.println("Must execute");
        }
        System.out.println("Thank you");
    }
}

Java program for an array with a method

public class ArrayFunction
{
    int i, j, f;
    int searchResult(int m[], int s)
    {
        f=0;
        for(i=0; i<m.length; i++)
        {
            if(s==m[i])
            {
                f=1;
                break;
            }
        }
        return f;
    }


    public static void main(String args[])
    {
        int n[]={10, 3, 6, 5, 11, 7, 1, 17, 8, 9};
        int se=7, flag;
        ArrayFunction ob=new ArrayFunction();
        flag=ob.searchResult(n, se);
        if(flag==1)
        {
            System.out.println("Found");
        }
        else
        {
            System.out.println("Not Found");
        }

    }
}
In the above program, we have created one method of searching int searchResult(int m[], int s), in which we have send array and one value to search. 

Some more program

Binary Search in Java


Learn Java
Become An Awesome Java Professional