fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class Solution {
  6. public static void main (String[] args) throws java.lang.Exception {
  7. Scanner sc = new Scanner(System.in);
  8. int n = sc.nextInt();
  9.  
  10. int arr[] = new int[n];
  11. int maxnum = Integer.MIN_VALUE;
  12. for (int i = 0; i < n; i++) {
  13. arr[i] = sc.nextInt();
  14. maxnum = Math.max(arr[i], maxnum);
  15. }
  16.  
  17. int max = maxnum;
  18.  
  19. List<Integer> ls[] = new ArrayList[max + 1];
  20. for (int i = 1; i <= max; i++)
  21. ls[i] = new ArrayList<>();
  22. for (int i = 1; i <= max; i++) {
  23. for (int j = i; j <= max; j += i)
  24. ls[j].add(i);
  25. }
  26.  
  27. HashMap<Integer, Integer> freq = new HashMap<>();
  28. for (int v : arr)
  29. freq.put(v, freq.getOrDefault(v, 0) + 1);
  30.  
  31. HashMap<Integer, Integer> hm = new HashMap<>();
  32. for (int v : freq.keySet()) {
  33. int cnt = freq.get(v);
  34. for (int d : ls[v])
  35. hm.put(d, hm.getOrDefault(d, 0) + cnt);
  36. }
  37.  
  38. for(int i = 1; i <= maxnum; i++) {
  39. int count = hm.getOrDefault(i, 0);
  40. System.out.print(i + " -> " + count + " (");
  41. for(int v : arr) {
  42. if(v % i == 0)
  43. System.out.print(v + " ");
  44. }
  45. System.out.println(")");
  46. }
  47. }
  48. }
  49.  
Success #stdin #stdout 0.19s 60856KB
stdin
5
2 4 6 3 9
stdout
1 -> 5 (2 4 6 3 9 )
2 -> 3 (2 4 6 )
3 -> 3 (6 3 9 )
4 -> 1 (4 )
5 -> 0 ()
6 -> 1 (6 )
7 -> 0 ()
8 -> 0 ()
9 -> 1 (9 )