JavaScript Program to Generate a matrix having sum of secondary diagonal equal to a perfect square


We will write a JavaScript program that generates a matrix with the sum of the secondary diagonal being a perfect square. Our program will use nested loops to traverse the matrix and calculate the sum of the secondary diagonal elements. We will then use the Math.sqrt() method to find the square root of the sum and check if it is a whole number. If it is, we will consider the sum to be a perfect square.

Approach

The approach to generate a matrix with the sum of secondary diagonal equal to a perfect square is as follows −

  • Create a two-dimensional array of size n x n where n is the size of the square matrix.

  • Fill the matrix with random numbers between 1 and 100.

  • Calculate the sum of the secondary diagonal of the matrix.

  • Check if the sum is a perfect square or not. If it's not a perfect square, generate a new matrix and repeat the steps 2 to 4.

  • Return the matrix with the secondary diagonal sum equal to a perfect square.

  • To check if the number is a perfect square, you can use the Math.sqrt() function and compare its result with the integer value of the square root.

Example

Here is an example of a JavaScript program that generates a matrix with the sum of its secondary diagonal equal to a perfect square −

function generateMatrix(n) {
   let matrix = [];
   for (let i = 0; i < n; i++) {
      matrix[i] = [];
      for (let j = 0; j < n; j++) {
         matrix[i][j] = i * n + j + 1;
      }
   }
   let sum = 0;
   for (let i = 0; i < n; i++) {
      sum += matrix[i][n - i - 1];
   }
   let squareRoot = Math.floor(Math.sqrt(sum));
   if (squareRoot * squareRoot !== sum) {
      return null;
   }
   return matrix;
}

const n = 1;
console.log(generateMatrix(n));

Explanation

  • The generateMatrix function takes in a single argument n which represents the size of the matrix to be generated.

  • The function initializes an empty 2D array matrix and loops through each row and column to fill the matrix with numbers i * n + j + 1, where i is the row number and j is the column number.

  • The function calculates the sum of the secondary diagonal of the matrix by looping through each row and column, adding up the values at the indices (i, n - i - 1), where i is the row number.

  • The function calculates the square root of the sum and rounds down to the nearest integer. If the square of this integer is not equal to the sum, the function returns null, indicating that the sum is not a perfect square.

  • If the sum is a perfect square, the function returns the generated matrix.

Updated on: 15-Mar-2023

135 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements