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: Refer to this article for the simplest approach to solve the problem by constructing the given matrix by multiplying the row and column indices to obtain each matrix element and count the number of occurrences of X.
Time Complexity: O(N2)
Auxiliary Space: O(N2)
Efficient Approach: The idea is based on the observation that the ith row contains all the multiples of i in the range [1, N]. Therefore, X occurs in the ith row if and only if X is exactly divisible by i and X / i should be less than or equal to N. If found to be true, increment the count by 1. 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, N] using the variable i and perform the following steps:
- If X is divisible by i, store the quotient of X / i in a variable, say b.
- If the value of b falls in the range [1, N], then increase the count by 1.
- After completing the above steps, print the value of count as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.