Count of factors of length K in the number itself
Given an integer N and a value K, the task is to find the number of factors of length K that are present in the number itself.
Examples:
Input: N = 120, K = 2
Output: 2
Explanation: 12 (120), 20 (120). Both are factors of 120.Input: N = 21, K = 2
Output: 1
Approach: The problem can be solved greedily using the following idea:
Find all the K-length numbers that can be generated from the number and check how many of them are factors of N.
Follow the steps mentioned below to implement the idea:
- Iterate the number.
- Initialize the start index with 0.
- Slice the number for K size from the start index.
- Then check if the sliced part of the number is a factor of the given number.
- If it is a factor, increment the counter.
- Else, do nothing.
- Increment the start index to the next index.
- Continue the above process until the start index is N-K.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach #include <bits/stdc++.h>using namespace std; // Function to find the number of factorsint countFactorsinNum(int num, int k){ string str = to_string(num); int N = str.size(); int ctr = 0; int i = 0; while (i <= N - k) { // substr(from where, nos of chars) string s2 = str.substr(i, k); int val = stoi(s2); // val!=0 to avoid div by 0 error if (val != 0 && num % val == 0) { ctr++; } i = i + 1; } return ctr;} // Driver codeint main(){ int N = 120, K = 2; // Function call cout << countFactorsinNum(N, K) << "\n"; return 0;} |
Output
2
Time Complexity: O(d) where d is the number of digits
Auxiliary Space: O(1)
Related Articles:





Please Login to comment...