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
}
}
'Computer Science > Algorithm with Code' 카테고리의 다른 글
[HackerRank] Preparation_Kit (01. Sales by Match) (0) | 2024.09.14 |
---|---|
Leet Code (2405. Amazon Spring '23 HF) (0) | 2024.05.13 |
Hacker Rank_5/54 tests (Easy, Lonely Integer) (0) | 2024.05.09 |
Hacker Rank_4/54 tests (Easy, Sparse Array) (0) | 2024.05.09 |
Hacker Rank_3/54 tests (Easy, Time Conversion) (0) | 2024.05.08 |