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

26 Apr, 2021
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.
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.
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:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to count the occurrences// of X in the generated square matrixint countOccurrences(int N, int X){         // Stores the required result    int count = 0;     //Iterate upto square root of X    for (int i = 1; i < sqrt(X); i++)    {                 // Check if i divides X        if (X % i == 0)        {                         // Store the quotient obtained            // on dividing X by i            int a = i;            int b = X / i;             // If both the numbers fall in            // the range, update count            if (a <= N && b <= N)            {                if (a == b)                    count += 1;                else                    count += 2;            }        }    }         // Return the result    return count;} // Driver codeint main(){         // Given N and X    int N = 7;    int X = 12;         // Function Call    cout << countOccurrences(N, X);         return 0;} // This code is contributed by mohit kumar 29
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG {   // Function to count the occurrences  // of X in the generated square matrix  static int countOccurrences(int N, int X)  {     // Stores the required result    int count = 0;     // Iterate upto square root of X    for (int i = 1; i < Math.sqrt(X); i++) {       // Check if i divides X      if (X % i == 0) {         // Store the quotient obtained        // on dividing X by i        int a = i;        int b = X / i;         // If both the numbers fall in        // the range, update count        if (a <= N && b <= N) {          if (a == b)            count += 1;          else            count += 2;        }      }    }     // Return the result    return count;  }   // Driver code  public static void main(String[] args)  {     // Given N and X    int N = 7;    int X = 12;     // Function Call    System.out.println(countOccurrences(N, X));  }} // This code is contributed by Kingsh.
# Python3 program for the above approachfrom math import sqrt # Function to count the occurrences# of X in the generated square matrixdef countOccurrences(N, X):     # Stores the required result    count = 0     # Iterate upto square root of X    for i in range(1, int(sqrt(X))+1):         # Check if i divides X        if X % i == 0:             # Store the quotient obtained            # on dividing X by i            a = i            b = X//i             # If both the numbers fall in            # the range, update count            if a <= N and b <= N:                if a == b:                    count += 1                else:                    count += 2     # Return the result    return count  # Driver Codeif __name__ == '__main__':     # Given N and X    N = 7    X = 12     # Function Call    print(countOccurrences(N, X))
// C# program for above approachusing System;public class GFG{   // Function to count the occurrences  // of X in the generated square matrix  static int countOccurrences(int N, int X)  {     // Stores the required result    int count = 0;     // Iterate upto square root of X    for (int i = 1; i < Math.Sqrt(X); i++) {       // Check if i divides X      if (X % i == 0) {         // Store the quotient obtained        // on dividing X by i        int a = i;        int b = X / i;         // If both the numbers fall in        // the range, update count        if (a <= N && b <= N) {          if (a == b)            count += 1;          else            count += 2;        }      }    }     // Return the result    return count;  }   // Driver code  public static void Main(String[] args)  {    // Given N and X    int N = 7;    int X = 12;     // Function Call    Console.Write(countOccurrences(N, X));  }} // This code is contributed by code_hunt.
<script> // Javascript program for the above approach // Function to count the occurrences// of X in the generated square matrixfunction countOccurrences(N, X){         // Stores the required result    var count = 0;     //Iterate upto square root of X    for (var i = 1; i < Math.sqrt(X); i++)    {                 // Check if i divides X        if (X % i == 0)        {                         // Store the quotient obtained            // on dividing X by i            var a = i;            var b = X / i;             // If both the numbers fall in            // the range, update count            if (a <= N && b <= N)            {                if (a == b)                    count += 1;                else                    count += 2;            }        }    }         // Return the result    return count;} // Driver code// Given N and Xvar N = 7;var X = 12; // Function Calldocument.write( countOccurrences(N, X)); </script>
4
 
Time Complexity: O(√X)Auxiliary Space: O(1)
mohit kumar 29
Kingash
code_hunt
itsok
number-theory
Greedy
Mathematical
Matrix
Pattern Searching
number-theory
Greedy
Mathematical
Matrix
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for First Fit algorithm in Memory Management
Program for Best Fit algorithm in Memory Management
Optimal Page Replacement Algorithm
Program for Worst Fit algorithm in Memory Management
Max Flow Problem Introduction
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples