‹ Back to the paper
A class Composite contains a two-dimensional array of order [m x n]. The maximum values possible…
A class Composite contains a two-dimensional array of order [m x n]. The maximum values possible for both ‘m’ and ‘n’ is 20. Design a class Composite to fill the array with the first (m x n) composite numbers in column wise.
[Composite numbers are those which have more than two factors.]
The details of the members of the class are given below:
Class name : Composite
Data members/instance variables:
arr[ ][ ] : integer array to store the composite numbers column wise
m : integer to store the number of rows
n : integer to store the number of columns
Member functions/methods:
Composite(int mm, int nn ) : to initialize the size of the matrix, m=mm and n=nn
int isComposite( int p ) : to return 1 if the number is composite otherwise returns 0
void fill ( ) : to fill the elements of the array with the first (m × n) composite numbers in column wise
void display( ) : to display the array in a matrix form
Specify the class Composite giving details of the constructor(int,int), int isComposite(int), void fill( ) and void display( ). Define a main( ) function to create an object and call all the functions accordingly to enable the task.
Answer
Answer
AIclass Composite
{
int arr[][];
int m, n;
Composite(int mm, int nn)
{
m = mm;
n = nn;
arr = new int[m][n];
}
int isComposite(int p)
{
if (p < 4)
return 0;
int count = 0;
for (int i = 1; i <= p; i++)
if (p % i == 0)
count++;
return (count > 2) ? 1 : 0;
}
void fill()
{
int num = 3;
for (int j = 0; j < n; j++)
{
for (int i = 0; i < m; i++)
{
num++;
while (isComposite(num) == 0)
num++;
arr[i][j] = num;
}
}
}
void display()
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
System.out.print(arr[i][j] + "\t");
System.out.println();
}
}
public static void main(String args[])
{
Composite obj = new Composite(3, 3);
obj.fill();
obj.display();
}
}Explanation: isComposite(p) counts all factors of p from 1 to p; a count greater than 2 means p is composite. fill() searches upward from 4 for successive composite numbers and stores them column by column (outer loop over columns j, inner loop over rows i), so the array is filled with the first m*n composite numbers in column-major order. Tested (run for real) with m=n=3: the first 9 composite numbers 4,6,8,9,10,12,14,15,16 were placed column-wise, and display() printed:
4 9 14
6 10 15
8 12 16From ISC 2024 Specimen Computer Science Paper 1, question 7.