Function isNP(Nb As Double) As Boolean
' TEST SI NB EST UN NOMBRE PREMIER ( ALGO RAPIDE )
' utilise ERATHOSENE et DIVISIONS
' Test de validité
If Nb < 2 Then Exit Function
' Paramères
Dim Liste As Long, Saut As Long, t As Long
Dim A As Long, A1 As Long, A2 As Long
Dim Nbp() As Boolean, L() As Long
Dim Pi_NbP As Long, bs As Double, Pi_Nbp2 As Long
Dim Prod As Double
' Paramètres d'optimisation
Pi_NbP = 5 'indice de 0 à 5
Prod = 30030 'produit de 2*3*5*7*11*13
' ALGO ERATHOSTENE : Génére liste nb premier jusqu'à pi(A+1)
A = Prod + 1
A1 = Int((A ^ 0.5 - 3) / 2)
A2 = Int((A - 3) / 2)
ReDim Nbp(A2)
For Liste = 0 To A1
If Nbp(Liste) = False Then
Saut = 2 * Liste + 3
For t = (Saut ^ 2 - 3) / 2 To A2 Step Saut
Nbp(t) = True 'pas premier
Next t
End If
Next Liste
' Forme la liste
ReDim L(A2 + 1)
L(0) = 2
Pi_Nbp2 = 0
For t = 0 To A2
If Nbp(t) = False Then
Pi_Nbp2 = Pi_Nbp2 + 1
L(Pi_Nbp2) = 2 * t + 3
End If
Next t
' Test si trivial
If Nb > Prod Then GoTo suite 'évite si pas nécessaire
For t = 0 To Pi_Nbp2
If Nb = L(t) Then isNP = True: Exit Function
Next t
suite:
' Test si multiple
For t = 0 To Pi_Nbp2
If Nb = L(t) * Int(Nb / L(t)) Then Exit Function
Next t
' Forme liste complète
Dim nbp2 As Long
ReDim L2(5627)
For t = Pi_NbP + 1 To Pi_Nbp2
nbp2 = nbp2 + 1
L2(nbp2) = L(t)
Next t
' On rajoute les multiples
Dim t2 As Long
For t = Pi_NbP + 1 To Pi_Nbp2
If L(t) * L(t) > A Then Exit For
For t2 = t To Pi_Nbp2
If L(t) * L(t2) < A Then
nbp2 = nbp2 + 1
L2(nbp2) = L(t) * L(t2)
Else
Exit For
End If
Next t2
Next t
' ALGO DIVISIONS
Dim fin As Long, m As Long
fin = Sqr(Nb)
For m = 0 To fin Step Prod
For t = 1 To nbp2
If Nb = (m + L2(t)) * Int(Nb / (m + L2(t))) Then Exit Function
Next t
Next m
isNP = True
End Function