Find time complexity for kth factor
Manoj Kumar Shukla
Manoj Kumar Shukla
Engineering @ Siemens Healthineers | Proficient in C++, JavaScript, RDBMS, OOPs and Python
Below given 2 example for finding the kth factor of a number n. Both has the time complexity of O(n) but for large number which one according to you will perform better and why?
leetcode question - https://tinyurl.com/42s34thv
Let me know in the comment section...
领英推荐
Example 1:
class Solution {
public:
int kthFactor(int n, int k) {
for( int i=1; i<=n/2; i++) {
if(n%i == 0) {
k--;
if( k < 0 ) return -1;
if( k == 0 ) return i;
}
}
k--;
if( k == 0) return n;
return -1;
}
};
Example 2 :
class Solution {
public:
int kthFactor(int n, int k) {
set<int> st;
for( int i=1; i<=n/2; i++)
if(n%i == 0)
st.insert(i);
st.insert(n);
if( st.size() < k )
return -1;
k--;
while(k--) {
st.erase( st.begin() );
}
return *st.begin();
}
};
Engineering @ Siemens Healthineers | Proficient in C++, JavaScript, RDBMS, OOPs and Python
1 年Below are the time complexities of Example 1 and Example 2