Find time complexity for kth factor

Find time complexity for kth factor

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();
    }
};        
Manoj Kumar Shukla

Engineering @ Siemens Healthineers | Proficient in C++, JavaScript, RDBMS, OOPs and Python

1 年

Below are the time complexities of Example 1 and Example 2

  • 该图片无替代文字

要查看或添加评论,请登录

社区洞察

其他会员也浏览了