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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public: intkthFactor(int n, int k){ vector<int> factors; for(int i = 1; i * i <= n && factors.size() <= k; i++) { if(!(n % i)) factors.push_back(i); }
return factors.empty() ? -1 : factors.size() >= k ? factors[k - 1] : factors.back() * factors.back() == n ? (factors.size() << 1) - 1 >= k ? n / factors[(factors.size() << 1) - k - 1] : -1 : (factors.size() << 1) >= k ? n / factors[(factors.size() << 1) - k] : -1; } };