Java Program to Create a Matrix and Fill it with Prime Numbers
Prime Numbers are the number which can be divisible by only 1 and itself, it cannot be divisible by any other number. The task here is to find the prime numbers and store them in the form of a matrix.
Example:
Prime numbers are: 2, 3, 5, 7
Output:
2 3
5 7
Prime numbers : 2, 3, 5, 7, 9, 11, 13, 17, 19
Output:
2 3 5
7 9 11
13 17 19
Approach:
- First, the class should be created and inside the class a method is created to check the prime number.
- This method will take the number as input and then check whether it is prime or not. If it is prime then it will return true and if not then return false.
- Now, the main method will be created, inside the main method the object of Matrix class is made so that the isPrime() method can be accessed from the main.
- The number of rows and number of columns will be taken from the user and then using this, the another array will be created which is of size rows * columns.
- The prime numbers will be stored in this array.
- Now, by iterating through result[] array, the prime numbers will gets stored into the Matrix[] array. After that the result will gets printed.
Java
import java.util.Scanner;
public class MatrixWithPrimeNumbers {
boolean isPrime( int num)
{
int counter = 0 ;
for ( int i = 1 ; i <= num; i++)
{
if (num % i == 0 )
counter = counter + 1 ;
}
if (counter == 2 )
return true ;
else
return false ;
}
public static void main(String args[])
{
MatrixWithPrimeNumbers mwp
= new MatrixWithPrimeNumbers();
int row = 4 ;
int col = 4 ;
int Matrix[][] = new int [row][col];
int res = row * col;
int Result[] = new int [res];
int i = 0 , j;
int k = 1 ;
while (i < res)
{
if (mwp.isPrime(k) == true )
{
Result[i] = k;
i++;
}
k++;
}
int x = 0 ;
for (i = 0 ; i < row; i++)
{
for (j = 0 ; j < col; j++)
{
Matrix[i][j] = Result[x];
x++;
}
}
System.out.println( "The Resultant Matrix is : " );
for (i = 0 ; i < row; i++)
{
for (j = 0 ; j < col; j++)
{
System.out.print(Matrix[i][j] + " " );
}
System.out.println();
}
}
}
|
Output
The Resultant Matrix is :
2 3 5 7
11 13 17 19
23 29 31 37
41 43 47 53
Last Updated :
13 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...