fork download
  1. import java.util.*;
  2. import java.util.Collections;
  3.  
  4. public class Main {
  5. public static ArrayList<Long> getSortedDivisors(long n) {
  6. ArrayList<Long> divisors = new ArrayList<>();
  7. for (long i = 1; i * i <= n; i++) {
  8. if (n % i == 0) {
  9. divisors.add(i);
  10. }
  11. }
  12. for (int i = divisors.size() - 1; i >= 0; i--) {
  13. long smallerDivisor = divisors.get(i);
  14. if (n / smallerDivisor != smallerDivisor) {
  15. divisors.add(n / smallerDivisor);
  16. }
  17. }
  18. return divisors;
  19. }
  20.  
  21. public static void main(String[] args) {
  22. Scanner sc=new Scanner(System.in);
  23. int n = sc.nextInt();
  24. ArrayList<Long> divisors = getSortedDivisors(n);
  25. Collections.reverse(divisors);
  26. System.out.print("Factors of "+n+" are : ");
  27. for (long divisor : divisors) {
  28. System.out.print(divisor + " ");
  29. }
  30. }
  31. }
  32.  
Success #stdin #stdout 0.18s 60932KB
stdin
18
stdout
Factors of 18 are : 18 9 6 3 2 1