Open In App

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

Last Updated : 27 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer N, the task is to generate a matrix of dimensions N x N using positive integers from the range [1, N] such that the sum of the secondary diagonal is a perfect square.

Examples:

Input: N = 3
Output:
1 2 3
2 3 1
3 2 1
Explanation:
The sum of secondary diagonal = 3 + 3 + 3 = 9(= 32).

Input: N = 7
Output:
1 2 3 4 5 6 7
2 3 4 5 6 7 1
3 4 5 6 7 1 2
4 5 6 7 1 2 3
5 6 7 1 2 3 4
6 7 1 2 3 4 5
7 1 2 3 4 5 6
Explanation:
The sum of secondary diagonal = 7 + 7 + 7 + 7 + 7 + 7 + 7 = 49(= 72).

Approach: Since the generated matrix needs to be of dimensions N x N, therefore, to make the sum of elements in the secondary diagonal a perfect square, the idea is to assign N at each index of the secondary diagonal. Therefore, the sum of all N elements in this diagonal is N2, which is a perfect square. Follow the steps below to solve the problem:

  1. Initialize a matrix mat[][] of dimension N x N.
  2. Initialize the first row of the matrix as {1 2 3 … N}.
  3. Now for the remaining rows of the matrix, fill each row by circular left shift of the arrangement of the previous row of the matrix by 1.
  4. Print the matrix after completing the above steps.

Below is the implementation of the above approach:

Java




// Java program for the above approach
class GFG {
  
    // Function to print the matrix whose sum
    // of element in secondary diagonal is a
    // perfect square
    static void diagonalSumPerfectSquare(int[] arr, 
                                         int N)
    {
  
        // Iterate for next N - 1 rows
        for (int i = 0; i < N; i++)
        {
  
            // Print the current row after
            // the left shift
            for (int j = 0; j < N; j++)
            {
                System.out.print(arr[(j + i) % 7] + " ");
            }
            System.out.println();
        }
    }
  
    // Driver Code
    public static void main(String[] srgs)
    {
  
        // Given N
        int N = 7;
  
        int[] arr = new int[N];
  
        // Fill the array with elements
        // ranging from 1 to N
        for (int i = 0; i < N; i++)
        {
            arr[i] = i + 1;
        }
  
        // Function Call
        diagonalSumPerfectSquare(arr, N);
    }
}
  
// This code is contributed by Amit Katiyar


Output

1 2 3 4 5 6 7 
2 3 4 5 6 7 1 
3 4 5 6 7 1 2 
4 5 6 7 1 2 3 
5 6 7 1 2 3 4 
6 7 1 2 3 4 5 
7 1 2 3 4 5 6 

Time Complexity: O(N2)
Auxiliary Space: O(N)

Please refer complete article on Generate a matrix having sum of secondary diagonal equal to a perfect square for more details!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads