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

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

To achieve this, let's break down the problem:

  1. The secondary diagonal of a matrix starts from the top-right corner and ends at the bottom-left corner.
  2. We need to ensure that the sum of elements of this diagonal is a perfect square.
  3. This means after generating or filling the matrix, we'll check the sum and adjust one of the values (preferably the bottom-left one) to make sure the sum becomes a perfect square.

Here's a Python program to generate a 3��3 matrix where the sum of the secondary diagonal elements equals a perfect square:

import random def is_perfect_square(num): return int(num**0.5 + 0.5) ** 2 == num def generate_matrix(): matrix = [[random.randint(1, 10) for _ in range(3)] for _ in range(3)] # Compute the sum of the secondary diagonal sec_diag_sum = sum(matrix[i][2-i] for i in range(3)) # Find the nearest perfect square greater than sec_diag_sum while not is_perfect_square(sec_diag_sum): sec_diag_sum += 1 # Adjust the bottom-left element to ensure the sum of the secondary diagonal is a perfect square matrix[2][0] = matrix[2][0] + (sec_diag_sum - sum(matrix[i][2-i] for i in range(3))) return matrix matrix = generate_matrix() for row in matrix: print(row) print("Sum of secondary diagonal:", sum(matrix[i][2-i] for i in range(3))) 

This program:

  1. Uses random.randint() to generate matrix values.
  2. Adjusts the bottom-left element of the matrix to ensure the sum of the secondary diagonal is a perfect square.
  3. Prints out the generated matrix and the sum of its secondary diagonal.

Note: This program works for a 3��3 matrix. If you have a different size in mind, you might need to adjust the indexing accordingly.


More Tags

replaceall voice-recognition docker viewaction inspector window-resize chisel pdf-extraction flex3 multibranch-pipeline

More Programming Guides

Other Guides

More Programming Examples