count_in_factors.sf 690 B

123456789101112131415161718192021222324252627282930313233343536
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Count_in_factors
  4. #
  5. class Counter {
  6. method factors(n, p=2) {
  7. var a = gather {
  8. while (n >= p*p) {
  9. while (p `divides` n) {
  10. take(p)
  11. n //= p
  12. }
  13. p = self.next_prime(p)
  14. }
  15. }
  16. (n > 1 || a.is_empty) ? (a << n) : a
  17. }
  18.  
  19. method is_prime(n) {
  20. self.factors(n).len == 1
  21. }
  22.  
  23. method next_prime(p) {
  24. do {
  25. p == 2 ? (p = 3) : (p+=2)
  26. } while (!self.is_prime(p))
  27. return p
  28. }
  29. }
  30.  
  31. for i in (1..100) {
  32. say "#{i} = #{Counter().factors(i).join(' × ')}"
  33. }