sweet1cris

Untitled

Oct 14th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6.  
  7. public class KthSmallestFactor {
  8.     public static void main(String[] args) throws Exception {
  9.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  10.         int t = Integer.parseInt(br.readLine());
  11.         long num;
  12.         int k;
  13.         for (int i = 0; i <= t; i++) {
  14.             String[] l = br.readLine().split(" ");
  15.             num = Long.parseLong(l[0]);
  16.             k = Integer.parseInt(l[1]);
  17.             System.out.println("result " + kthSmallest(num, k));
  18.         }
  19.     }
  20.  
  21.     public static long kthSmallest(long num, int k) {
  22.         int incrementer = num % 2 == 0 ? 1 : 2;
  23.         int count = 0;
  24.         List<Long> list = new ArrayList<>();
  25.         for (long i = 1; i <= Math.sqrt(num); i += incrementer) {
  26.             if (num % i == 0) {
  27.                 count++;
  28.                 if (count == k) {
  29.                     return i;
  30.                 }
  31.                 list.add(i);
  32.                 if (i != num / i) {
  33.                     list.add((num / i));
  34.                 }
  35.             }
  36.         }
  37.         Collections.sort(list);
  38.         if (k - 1 < list.size()) {
  39.             return list.get((int) (k - 1));
  40.         }
  41.         return -1;
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment