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.
Example 1:
Input: num=24, k=5
Output: 6 //Factor= 1,2,3,4,6,8,12,24
Approach
Java
import java.util.ArrayList;public class KthFactor {public static void main(String[] args) {int num = 24;int k = 5;int fact = kthFactor(num, k);System.out.println("Kth factor is " + fact);}public static int kthFactor(int n, int k) {//array list to hold the factor of the// given numberArrayList<Integer> r = new ArrayList<>();int i = 1;while (i <= n) {if (n % i == 0)r.add(i);i++;}//if factors are less//then k then return -1if (r.size() < k)return -1;//if factors are greater than or//equal to k return r[k-1]elsereturn r.get(k - 1);}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the//kth factor of given numberint kthFactor(int num,int k){//vector to hold the factor of the given//numbervector<int> factor;for(int i=1;i*i<=num;i++){//if i divides numif(num%i==0){//if num/i ==i then push only//one into the factorif(num/i==i)factor.push_back(i);//else push both fatcorselse{factor.push_back(i);factor.push_back(num/i);}}}//sort the factor arraysort(factor.begin(),factor.end());//if factors are less//then k then return -1if(factor.size()<k)return -1;//if factors are greater than or//equal to k return factor[k-1]elsereturn factor[k-1];}int main(){int num=24;int k=5;int fact=kthFactor(num,k);cout<<"Kth factor is ";cout<<fact<<"\n";return 0;}
No comments:
Post a Comment