Excel 函数在VBA中给我素数不起作用
我尝试了这个函数来给我素数,但它不起作用。我想不出什么。在JS中我可以很容易地做到这一点,但在这里它只是让我头痛Excel 函数在VBA中给我素数不起作用,excel,vba,Excel,Vba,我尝试了这个函数来给我素数,但它不起作用。我想不出什么。在JS中我可以很容易地做到这一点,但在这里它只是让我头痛 Function JeLiProst(N As Integer) As Boolean If N = 0 Then JeLiProst = False If N = 1 Then JeLiProst = False If N = 2 Then JeLiProst = True For I = 2 To N - 1 If N Mod I = 0 Then JeLiProst = Fa
Function JeLiProst(N As Integer) As Boolean
If N = 0 Then JeLiProst = False
If N = 1 Then JeLiProst = False
If N = 2 Then JeLiProst = True
For I = 2 To N - 1
If N Mod I = 0 Then
JeLiProst = False
Else
JeLiProst = True
End If
End Function
此函数是否满足您的要求
Function JeLiProst(N As Integer) As Boolean
Dim Primes As Variant
Dim i As Integer
' prime numbers below 50. Extend if required.
Primes = Array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47)
If N > 1 Then
For i = 0 To UBound(Primes)
If Primes(i) > N Then
JeLiProst = True
Exit For
Else
If (N Mod Primes(i)) = 0 Then
JeLiProst = (N = Primes(i))
Exit For
End If
End If
Next i
If i > UBound(Primes) Then
MsgBox N & " appears to be a prime number but I lack" & vbCr & _
"the data to assert that as a definite fact." & vbCr & _
"I shall classify it as 'not prime'.", _
vbInformation, "Insufficient stored data"
End If
Else
JeLiProst = True
End If
End Function
我已经有一百万年没有使用vba了,但是当N Mod I=0为真时,你不应该打破循环并用false退出函数吗?并且下一个I丢失了。可能是@JoakimDanielson的副本老实说,我试过这么做,因为I=2到N-1如果N Mod I=0,那么就转到Fal Next JeLiProst=true Fal:JeLiProst=false没有什么作用,现在,即使2=真实条件有效,我或判断这是重复的社区成员也不理解这个问题。在我看来,引用的副本与这个问题没有任何相似之处。我已经贴出了答案。让OP决定它是否有用。