Problem 41

Problem 41

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

require "prime" P = Prime.each digits = (1..9).map(&:to_s) loop do prime = P.next.to_s puts prime if digits[0, prime.size].all? {|d| prime[d]} end
Po jakims czasie sie zatrzymalo :wink:

[code=ruby]def eratostenes(n)
sieve = Array.new(n, true)
sieve[0],sieve[1] = nil,nil
3.step(n,2) {|c| (2*c).step(n,c){|i| sieve[i]=false if sieve[i]}}
return [2] + (3…n).select{|i| i if sieve[i] == true && i.odd?}
end

p eratostenes(10_000_000).select{|t| t if (1…7).to_a.all?{|num| t.to_s =~ /#{num}/} }.sort.last[/code]
Co ciekawe bardziej tradycyjna implementacja sita eratostenesa jest dwukrotnie szybsza:

def eratostenes(n) sito = Array.new(n, true) sito[0],sito[1],sito[2] = nil,nil,true i = 3 while i <= n do unless sito[i]==nil then j = 2*i while j <= n sito[j] = nil j += i end end i += 2 end return [2] + (3..n).select{|i| sito[i] == true && i.odd?} end