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).
Input: N = 5, X = 6
The 2D array formed is equal to the :
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
There are 2 occurrences of the element X(= 6) in the generated array.
Input: N = 7, X = 12
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:
Time Complexity: O(√X)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.