Suppose you have a multiplication table that is N by N. That is, a 2D array where the value at the i
-th row and j
-th column is (i + 1) * (j + 1)
(if 0-indexed) or i * j
(if 1-indexed).
Given integers N and X, write a function that returns the number of times X appears as a value in an N by N multiplication table.
For example, given N = 6 and X = 12, you should return 4, since the multiplication table looks like this:
| 1 | 2 | 3 | 4 | 5 | 6 |
| 2 | 4 | 6 | 8 | 10 | 12 |
| 3 | 6 | 9 | 12 | 15 | 18 |
| 4 | 8 | 12 | 16 | 20 | 24 |
| 5 | 10 | 15 | 20 | 25 | 30 |
| 6 | 12 | 18 | 24 | 30 | 36 |
And there are 4 12's in the table.
Example:
Input: n = 6, x= 12
Output: 4
Approach 1:
C++
#include <bits/stdc++.h>using namespace std;int findXAppearsinTable(int n, int x){if (x <= 0 || x > n * n){return 0;}int ans = 0;for (int i = 1; i <= n; i++){if (x % i == 0 && x / i <= n){ans++;}}return ans;}int main(){int n = 6;int x = 12;cout << findXAppearsinTable(n, x);return 0;}
Approach 2:
C++
#include <bits/stdc++.h>using namespace std;int findXAppearsinTable(int n, int x){vector<int> factors;if (x <= 0 || x > n * n){return 0;}//find all the factors of xfor (int i = 1; i * i <= x; i++){if (x % i == 0){if (i == x / i){factors.push_back(i);}else{factors.push_back(i);factors.push_back(x / i);}}}//sort the factorssort(factors.begin(), factors.end());int ans = 0;//if x is perfect squareif (sqrt(x) == int(sqrt(x))){ans++;}for (int i = 0; i < factors.size() / 2; i++){int a = factors[i];int b = factors[factors.size() - 1 - i];//if in the range then update answer//anwer will add 2 because the value occurs in//the pairif (a >= 1 && b <= n){ans += 2;}}return ans;}int main(){int n = 6;int x = 12;cout << findXAppearsinTable(n, x);return 0;}
No comments:
Post a Comment