generate_primes_with_digits_in_nondecreasing_order.sf 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 15 August 2021
  4. # https://github.com/trizen
  5. # Generate prime numbers that have digits in nondecreasing order.
  6. # See also:
  7. # https://rosettacode.org/wiki/Primes_with_digits_in_nondecreasing_order
  8. # OEIS sequences:
  9. # https://oeis.org/A028864 -- Primes with digits in nondecreasing order.
  10. # https://oeis.org/A345325 -- Number of primes less than 10^n with digits in nondecreasing order.
  11. func primes_with_nondecreasing_digits(upto, base = 10) {
  12. upto = prev_prime(upto+1)
  13. var list = []
  14. var digits = @(1..^base -> flip)
  15. var end_digits = digits.grep { .is_coprime(base) }
  16. list << digits.grep { .is_prime && !.is_coprime(base) }...
  17. for k in (0 .. upto.ilog(base)) {
  18. digits.combinations_with_repetition(k, {|*a|
  19. var v = a.digits2num(base)
  20. end_digits.each {|d|
  21. var n = (v*base + d)
  22. next if ((n >= base) && (a[0] > d))
  23. list << n if (n.is_prime && (n <= upto))
  24. }
  25. })
  26. }
  27. list.sort
  28. }
  29. say primes_with_nondecreasing_digits(1000)
  30. for k in (1..6) {
  31. var arr = primes_with_nondecreasing_digits(10**k)
  32. say "There are #{arr.len} primes with digits in nondecreasing order <= 10^#{k}"
  33. }
  34. __END__
  35. [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 37, 47, 59, 67, 79, 89, 113, 127, 137, 139, 149, 157, 167, 179, 199, 223, 227, 229, 233, 239, 257, 269, 277, 337, 347, 349, 359, 367, 379, 389, 449, 457, 467, 479, 499, 557, 569, 577, 599, 677]
  36. There are 4 primes with digits in nondecreasing order <= 10^1
  37. There are 16 primes with digits in nondecreasing order <= 10^2
  38. There are 50 primes with digits in nondecreasing order <= 10^3
  39. There are 132 primes with digits in nondecreasing order <= 10^4
  40. There are 315 primes with digits in nondecreasing order <= 10^5
  41. There are 689 primes with digits in nondecreasing order <= 10^6
  42. There are 1413 primes with digits in nondecreasing order <= 10^7
  43. There are 2636 primes with digits in nondecreasing order <= 10^8
  44. There are 4967 primes with digits in nondecreasing order <= 10^9
  45. There are 8563 primes with digits in nondecreasing order <= 10^10
  46. There are 14481 primes with digits in nondecreasing order <= 10^11
  47. There are 23593 primes with digits in nondecreasing order <= 10^12
  48. There are 37127 primes with digits in nondecreasing order <= 10^13