fork download
  1. import java.util.HashMap;
  2. import java.util.Map;
  3.  
  4. public class Main {
  5.  
  6. public static HashMap<Long, Long> primeFactors(long n) {
  7. HashMap<Long, Long> factorCount = new HashMap<>();
  8.  
  9. while (n % 2 == 0) {
  10. factorCount.put(2L, factorCount.getOrDefault(2L, 0L) + 1);
  11. n /= 2;
  12. }
  13.  
  14. for (long i = 3; i <= Math.sqrt(n); i += 2) {
  15. while (n % i == 0) {
  16. factorCount.put(i, factorCount.getOrDefault(i, 0L) + 1);
  17. n /= i;
  18. }
  19. }
  20.  
  21. if (n > 2) {
  22. factorCount.put(n, factorCount.getOrDefault(n, 0L) + 1);
  23. }
  24.  
  25. return factorCount;
  26. }
  27.  
  28. public static void main(String[] args) {
  29. long n =50;
  30. HashMap<Long, Long> factors = primeFactors(n);
  31.  
  32. for (Map.Entry<Long, Long> entry : factors.entrySet()) {
  33. System.out.println(entry.getKey() + " ^ " + entry.getValue());
  34. }
  35. }
  36. }
  37.  
Success #stdin #stdout 0.15s 57712KB
stdin
Standard input is empty
stdout
2 ^ 1
5 ^ 2