fork download
  1. # your code goes here
  2. def prime_factors(n):
  3. factors = {}
  4.  
  5. # Check for factor 2
  6. while n % 2 == 0:
  7. factors[2] = factors.get(2, 0) + 1
  8. n //= 2
  9.  
  10. # Check for odd factors starting from 3
  11. i = 3
  12. while i * i <= n:
  13. while n % i == 0:
  14. factors[i] = factors.get(i, 0) + 1
  15. n //= i
  16. i += 2
  17.  
  18. # If remaining n is a prime number greater than 2
  19. if n > 2:
  20. factors[n] = 1
  21.  
  22. return factors
  23.  
  24. # Example usage
  25. n = 18
  26. for factor, count in prime_factors(n).items():
  27. print(f"{factor} {count}")
Success #stdin #stdout 0.07s 14024KB
stdin
Standard input is empty
stdout
2 1
3 2