// UVa 10880 - Colin and Ryan import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { int cases = scanner.nextInt(); for (int caseNumber = 1; caseNumber <= cases; caseNumber++) { int C = scanner.nextInt(); int R = scanner.nextInt(); if (R == C) { System.out.printf("Case #%d: 0\n", caseNumber); continue; } List<Integer> factors = getAllFactors(C - R); int index = getInsertionPoint(R, factors); System.out.printf("Case #%d:", caseNumber); for (int i = index; i < factors.size(); i++) System.out.printf(" %d", factors.get(i)); System.out.printf("\n"); } } } private static List<Integer> getAllFactors(int n) { int limit = (int) Math.sqrt(n); List<Integer> factors = new ArrayList<>(); for (int d = 1; d < limit; d++) { if (n % d == 0) { factors.add(d); factors.add(n / d); } } if (n % limit == 0) { factors.add(limit); if (n / limit != limit) factors.add(n / limit); } Collections.sort(factors); return factors; } private static int getInsertionPoint(int R, List<Integer> factors) { int index = Collections.binarySearch(factors, R); if (index >= 0 && factors.get(index) == R) index++; else index = -(index + 1); return index; } }
Monday, January 2, 2017
UVa 10880 - Colin and Ryan
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment