본문 바로가기

Computer Science/Algorithm with Code

Leet Code (1492. Amazon Spring '23 HF)

1492. The kth Factor of n

 

You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.

Consider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.

: The kth factor (약수) of the n.

 

* Check The Test_Cases (Exceptions)

Could you solve this problem in less than O(n) complexity? 

class Solution {
    func kthFactor(_ n: Int, _ k: Int) -> Int {
        
        var c = 0
        var ans = 0
        
        for i in 1...n {
            if n%i == 0 {
                c += 1
            }
            if c == k {
                ans = i
                break
            }
            //if i == n/i { c += 1 } //If Duplicated number is included,
        }

        if c < k {
            ans = -1
        }
    	return ans
    }
}

 

https://leetcode.com/problems/the-kth-factor-of-n/description/?envType=study-plan-v2&envId=amazon-spring-23-high-frequency