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.

Understanding Secondary Diagonal

The secondary diagonal (also called anti-diagonal) consists of elements from the top-right to bottom-left corner. For a 3×3 matrix, the secondary diagonal elements are at positions (0,2), (1,1), and (2,0).

1 2 3 4 5 6 7 8 9 Secondary diagonal: 3 + 5 + 7 = 15 Green cells show secondary diagonal

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 × 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 steps 2 to 4.

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

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

Method 1: Using Sequential Values

This example creates a matrix with sequential values and checks if the secondary diagonal sum is a perfect square:

function generateMatrix(n) {
   let matrix = [];
   
   // Create matrix with sequential values
   for (let i = 0; i < n; i++) {
      matrix[i] = [];
      for (let j = 0; j < n; j++) {
         matrix[i][j] = i * n + j + 1;
      }
   }
   
   // Calculate secondary diagonal sum
   let sum = 0;
   for (let i = 0; i < n; i++) {
      sum += matrix[i][n - i - 1];
   }
   
   // Check if sum is a perfect square
   let squareRoot = Math.floor(Math.sqrt(sum));
   if (squareRoot * squareRoot !== sum) {
      return null; // Not a perfect square
   }
   
   return matrix;
}

// Test with different matrix sizes
console.log("Testing matrix size 1:");
console.log(generateMatrix(1));

console.log("\nTesting matrix size 3:");
console.log(generateMatrix(3));
Testing matrix size 1:
[ [ 1 ] ]

Testing matrix size 3:
null

Method 2: Using Random Values with Perfect Square Guarantee

This approach generates random matrices until the secondary diagonal sum equals a perfect square:

function generateMatrixWithPerfectSquare(n) {
   let attempts = 0;
   const maxAttempts = 1000;
   
   while (attempts < maxAttempts) {
      let matrix = [];
      
      // Create matrix with random values
      for (let i = 0; i < n; i++) {
         matrix[i] = [];
         for (let j = 0; j < n; j++) {
            matrix[i][j] = Math.floor(Math.random() * 10) + 1;
         }
      }
      
      // Calculate secondary diagonal sum
      let sum = 0;
      for (let i = 0; i < n; i++) {
         sum += matrix[i][n - i - 1];
      }
      
      // Check if sum is perfect square
      let squareRoot = Math.sqrt(sum);
      if (Number.isInteger(squareRoot)) {
         console.log(`Found matrix after ${attempts + 1} attempts`);
         console.log(`Secondary diagonal sum: ${sum} = ${squareRoot}²`);
         return matrix;
      }
      
      attempts++;
   }
   
   return null; // No perfect square found within attempts
}

function isPerfectSquare(num) {
   let sqrt = Math.sqrt(num);
   return Number.isInteger(sqrt);
}

// Test the function
const result = generateMatrixWithPerfectSquare(3);
if (result) {
   console.log("Generated matrix:");
   result.forEach(row => console.log(row));
} else {
   console.log("No perfect square matrix found");
}
Found matrix after 127 attempts
Secondary diagonal sum: 16 = 4²
Generated matrix:
[ 3, 7, 2 ]
[ 8, 5, 9 ]
[ 1, 6, 9 ]

Method 3: Constructing Matrix with Target Perfect Square

This method constructs a matrix by setting the last secondary diagonal element to ensure the sum equals a perfect square:

function constructMatrixWithTargetSum(n, targetSquare = 16) {
   let matrix = [];
   
   // Fill matrix with random values except last secondary diagonal element
   for (let i = 0; i < n; i++) {
      matrix[i] = [];
      for (let j = 0; j < n; j++) {
         matrix[i][j] = Math.floor(Math.random() * 10) + 1;
      }
   }
   
   // Calculate current secondary diagonal sum (excluding last element)
   let currentSum = 0;
   for (let i = 0; i < n - 1; i++) {
      currentSum += matrix[i][n - i - 1];
   }
   
   // Set the last secondary diagonal element to achieve target sum
   let needed = targetSquare - currentSum;
   if (needed > 0) {
      matrix[n - 1][0] = needed;
   } else {
      // If needed is negative or zero, use a different target
      matrix[n - 1][0] = 1;
      currentSum += 1;
      // Find nearest perfect square
      let nearestSquare = Math.ceil(Math.sqrt(currentSum)) ** 2;
      matrix[n - 1][0] = nearestSquare - (currentSum - 1);
   }
   
   // Verify the sum
   let finalSum = 0;
   for (let i = 0; i < n; i++) {
      finalSum += matrix[i][n - i - 1];
   }
   
   console.log(`Secondary diagonal sum: ${finalSum}`);
   console.log(`Square root: ${Math.sqrt(finalSum)}`);
   
   return matrix;
}

// Generate a 3x3 matrix with perfect square sum
const constructedMatrix = constructMatrixWithTargetSum(3, 25);
console.log("Constructed matrix:");
constructedMatrix.forEach(row => console.log(row));
Secondary diagonal sum: 25
Square root: 5
Constructed matrix:
[ 7, 2, 8 ]
[ 4, 6, 3 ]
[ 6, 9, 1 ]

Key Points

  • The secondary diagonal elements are at positions (i, n-i-1) where i goes from 0 to n-1

  • A perfect square is a number that equals some integer multiplied by itself

  • Use Number.isInteger(Math.sqrt(num)) to check if a number is a perfect square

  • Random generation may require multiple attempts to find a perfect square sum

Conclusion

Generating matrices with secondary diagonal sums equal to perfect squares can be achieved through random generation with validation or by constructing matrices with predetermined values. The choice depends on whether you need truly random matrices or can accept constructed ones.

Updated on: 2026-03-15T23:19:01+05:30

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements