fork download
  1. import java.util.*;
  2. import java.util.stream.*;
  3.  
  4. class FastFactoring
  5. {
  6. public static void main (String[] args)
  7. {
  8. long num = Integer.MAX_VALUE;
  9. Map<Long, Integer> factors = factorize(num);
  10.  
  11. //Printing out the map...
  12. System.out.printf("%d = ", num);
  13. if (factors.get(num) != null) {
  14. System.out.print("PRIME");
  15. } else {
  16. Iterator<Long> factorKeys = factors.keySet().iterator();
  17. for (int j = 0; j < factors.size(); j++) {
  18. long factor = factorKeys.next();
  19. int count = factors.get(factor);
  20. if (count > 1) {
  21. System.out.printf("%d^%d", factor, count);
  22. } else {
  23. System.out.printf("%d", factor);
  24. }
  25. if (j + 1 != factors.size()) {
  26. System.out.print("×");
  27. }
  28. }
  29. }
  30. System.out.println();
  31. }
  32.  
  33. public static Map<Long, Integer> factorize(long num) {
  34. Map<Long, Integer> factors = new LinkedHashMap<>();
  35. long n = num;
  36. for (long i = 2; i <= n / i; i++) {
  37. int count = 0;
  38. while (n % i == 0) {
  39. count++;
  40. n /= i;
  41. }
  42. if (count > 0) {
  43. factors.put(i, count);
  44.  
  45. }
  46. }
  47. if (n > 1) {
  48. factors.put(n, 1);
  49. }
  50. return factors;
  51. }
  52. }
Success #stdin #stdout 0.11s 321280KB
stdin
Standard input is empty
stdout
2147483647 = PRIME