Il est appelé algorithme am Sieve of Eratosthenes pour trouver nombre premier jusqu'à n
nombre. La complexité asymptotique est O (nlog (logn)).
Le pseudo-code est quelque chose comme:
- Créer un tableau à partir 0..MAX
- À partir de 2, supprimer chaque multiple de 2 à partir du tableau.
- Ensuite, revenez au début et supprimez tous les multiples de 3.
- Répétez cette opération à partir du prochain numéro disponible au début du tableau.
- Procédez ainsi jusqu'à ce que le carré du nombre que vous vérifiez soit supérieur à votre nombre maximal.
- Enfin, compactez la matrice d'origine.
Ce tableau contiendra uniquement les nombres premiers jusqu'à votre nombre maximal. Vous constaterez que c'est vraiment très efficace. Tellement efficace que vous pouvez l'utiliser comme une méthode d'assistance pour déterminer si un nombre est premier ou non. Voulez-vous savoir si le nombre 105557 est prioritaire? Seulement prend 66 étapes.
code Ruby:
def sieve(max)
# Set up an array with all the numbers from 0 to the max
primes = (0..max).to_a
# Set both the first and second positions (i.e., 0 and 1) to nil, as they
# aren't prime.
primes[0] = primes[1] = nil
# Iterate through primes array
counter = 0
primes.each do |p|
# Skip if nil
next unless p
# Break if we are past the square root of the max value
break if p*p > max
counter += 1
# Start at the square of the current number, and step through.
# Go up to the max value, by multiples of the current number, and replace
# that value with nil in the primes array
(p*p).step(max,p) { |m| primes[m] = nil }
end
# Finally, return the compacted array.
puts "Solved for #{max} in #{counter} steps."
primes.compact
end
Pour vérifier si un nombre est premier ou non:
def prime?(num)
sieve(num).include?(num)
end
Veuillez consulter: http://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime?rq=1 – mba12