as title says. want find left truncatable primes between 10 , 9999 using ruby language. following tried , gives me result.
require 'prime' require 'benchmark' trunc_primes = [] benchmark.bmbm |bm| bm.report{ prime.each(10000).each |num| is_tunc_prime = true (1..(num.to_s.length)).to_a.reverse.each |i| factor = 10 ** unless num.divmod(factor)[1].prime? is_tunc_prime = false break end end trunc_primes << num if is_tunc_prime end;nil } end
question: can script optimized further(lesser loops, use formula rather factor division technique) ?
benchmark stats:
➜ truncatable git:(master) ✗ ruby truncatable_primes.rb rehearsal ------------------------------------ 0.000000 0.000000 0.000000 ( 0.000026) --------------------------- total: 0.000000sec user system total real 0.000000 0.000000 0.000000 ( 0.000020) ➜ truncatable git:(master) ✗ ruby truncatable_primes.rb rehearsal ------------------------------------ 0.000000 0.000000 0.000000 ( 0.000024) --------------------------- total: 0.000000sec user system total real 0.000000 0.000000 0.000000 ( 0.000017) ➜ truncatable git:(master) ✗ ruby truncatable_primes.rb rehearsal ------------------------------------ 0.000000 0.000000 0.000000 ( 0.000028) --------------------------- total: 0.000000sec user system total real 0.000000 0.000000 0.000000 ( 0.000044) ➜ truncatable git:(master) ✗ ruby truncatable_primes.rb rehearsal ------------------------------------ 0.000000 0.000000 0.000000 ( 0.000030) --------------------------- total: 0.000000sec user system total real 0.000000 0.000000 0.000000 ( 0.000019)
benchmark above script , amadan's script
rehearsal ------------------------------------------ mine 0.020000 0.000000 0.020000 ( 0.022804) amadan 0.000000 0.000000 0.000000 ( 0.001559) --------------------------------- total: 0.020000sec user system total real mine 0.020000 0.000000 0.020000 ( 0.019625) amadan 0.000000 0.000000 0.000000 ( 0.001540)
since you're using prime
, why invent hot water?
prime.each(10000).reject { |p| p < 10 }.select { |p| s = p.to_s 1.upto(s.length - 1).all? { |i| s[i] != '0' && prime.prime?(s[i .. -1].to_i) } }
edit: can optimised further though - if abcd
turns out not truncatable prime, zabcd
not need tested:
require 'set' require 'prime' set.new.tap { |f| prime.each(10000) { |p| s = p.to_s f << p if p < 10 || (s[1] != '0' && f.include?(s[1 .. -1].to_i)) } }.reject { |p| p < 10 }
edit: forgot no zeroes requirement. added. being on mobile now, can't check if still running ok.
Comments
Post a Comment