# Count occurrences of an element in a matrix of size N * N generated such that each element is equal to product of its indices

Count occurrences of an element in a matrix of size N * N generated such that each element is equal to product of its indices

Given two positive integers N and X, the task is to count the occurrences of the given integer X in an N-length square matrix generated such that each element of the matrix is equal to the product of its row and column indices (1-based indexing).

Examples:

Input: N = 5, X = 6Output: 2Explanation:The 2D array formed is equal to the :1 2 3 4 52 4 6 8 103 6 9 12 154 8 12 16 205 10 15 20 25There are 2 occurrences of the element X(= 6) in the generated array.

Input: N = 7, X = 12Output: 4

Naive Approach: The simplest approach is to construct the given matrix by multiplying the row and column indices to obtain each matrix element. After generating the matrix, print the count of occurrences of X in the matrix.Time Complexity: O(N2)Auxiliary Space: O(N2)

Efficient Approach: To optimize the above approach, the idea is based on the observation that each element in the matrix is a product of 2 numbers. So, by checking for the number of ways X can be represented as a product of 2 numbers and selecting those pairs that lie over the range [1, N], gives the result. Follow the steps below to solve the problem:Initialize a variable, say count, to store the count of occurrences of X in the generated matrix.

Iterate over the range [1, √X] using the variable i and perform the following steps:

If the value of i divides X, store the quotient obtained on dividing X by i in a variable, say b.

If the value of both i and b fall in the range [1, N], then perform the following steps:

Check if i is equal to b or not. If found to be true, it means that X is a perfect square and the row and column will occur once. Hence, increase count by 1.

Otherwise, it means they will occur twice, once in a row and in a column the other time. Hence, increase count by 2.

After completing the above steps, print the value of count as the result.

Below is the implementation of the above approach:

Python3

from math import sqrt

def countOccurrences(N, X):

count = 0

for i in range(1, int(sqrt(X))+1):

if X % i == 0:

a = i

b = X//i

if a