代码如下,计算 x = 10000 y = 10000 只要 10 秒(用 exe 执行)
结果为 0.60794971
Private Sub Command1_Click()
Dim aPrime() As Long
初始化质数数组 aPrime
Dim start As Date, finish As Date
Dim aFlag() As Boolean
Dim x As Long
Dim y As Long
Dim minXY As Long
Dim i As Long
Dim p As Long
Dim m As Long, n As Long
Dim k As Long
x = Val(Text1)
y = Val(Text2)
start = Now
ReDim aFlag(1 To x, 1 To y)
minXY = IIf(x < y, x, y)
k = x * y
For i = 0 To UBound(aPrime)
p = aPrime(i)
If p > minXY Then Exit For
For m = p To x Step p
For n = p To y Step p
If Not aFlag(m, n) Then
k = k - 1
aFlag(m, n) = True
End If
Next
Next
Next
finish = Now
Me.Print x & "," & y, k / (x * y), DateDiff("s", start, finish)
End Sub
Function GETPMN(ByVal X As Long, Y As Long) As Double
Dim a() As Byte, i As Long, temp As Double, p As Long
If X > Y Then
temp = X
X = Y
Y = temp
End If
If X = 1 Then GETPMN = 1: Exit Function
GETPMN = 1 - ((X \ 2) / X) * ((Y \ 2) / Y)
ReDim a(1 To X)
p = 3
Do While p <= X
If p <= Sqr(X) Then
temp = p * p
k = 0
For i = temp To X Step 2 * p 'p的倍数
a(i) = 1 '设为1表示合数
Next
End If
GETPMN = GETPMN * (1 - ((X \ p) / X) * (Y \ p) / Y)
again:
p = p + 2
If p > X Then Exit Do
If a(p) = 1 Then GoTo again
Loop
End Function
Private Sub Command1_Click()
Dim mytime As Double
mytime = Timer
Debug.Print "x=20000000,y=10000000 时, m,n互质的概率为:" & GETPMN(20000000, 10000000); "总计用时 " & Format(Timer - mytime, "0.0000") & " 秒!"
辗转相除来求互质应该没什么问题的 谁能想出更简单的办法来估计可以拿**数学奖了
能做的简化也就只有getpmn
对于一个确定的X 假如它是2的倍数
那么对于Y 只有奇数才会是互质 而且肯定互质
对于一个确定的X 假如它是3的倍数
那么对于Y 只要Y Mod 3 And Y Mod 2 都不为0 就与3 互质
等于对Y进行了判断删选 应该可以快一点 如果有必要在加上5 7判断 当然判断多了可能也会增加时间
还有就是假如X,Y 相等的时候 可以再设计一下算法 嵌套循环的长度可以缩短
k = 0
For m = 1 To x
For n = m+1 To y
If ishuzhi(m, n) Then k = k + 1
Next
Next
k=2k+1
Private Sub Command1_Click()
Dim M As Long, i As Long, j As Long
M = IIf(CInt(Text1.Text) <= CInt(Text2.Text), CInt(Text2.Text), CInt(Text1.Text))
If IsPrime(M) Then
MsgBox "Since M is a prime, the result is Zero"
Exit Sub
End If
m_strPrimesM = GetPrimeExp(M)
For i = 2 To M - 1
If IsHuZhi(i) Then j = j + 1
Next i
MsgBox "The result is " & j & "/" & M - 2
End Sub
Private Function GetPrimeExp(ByVal Num1 As Long) As String
Dim Num2 As Long, i As Long
Dim strExp As String
For Num2 = 2 To Num1 - 1
If IsPrime(Num2) = True Then
Do While Num1 / Num2 = Num1 \ Num2
If strExp = "" Then
strExp = Num2
ElseIf InStr("*" & strExp & "*", "*" & Num2 & "*") = 0 Then
strExp = strExp & "*" & Num2
End If
Num1 = Num1 / Num2
Loop
End If
Next Num2
If strExp = "" Then strExp = Num1
GetPrimeExp = strExp
End Function
Private Function IsPrime(X As Long) As Boolean
Dim Y As Long
IsPrime = True
For Y = 2 To Sqr(X)
If X / Y = X \ Y Then
IsPrime = False
Y = X + 1
End If
Next Y
End Function
Private Function IsHuZhi(ByVal Num1 As Long) As Boolean
Dim i As Long
If Num1 = 2 Then Num1 = 3
For i = 2 To Num1 - 1
If IsPrime(i) Then
If Num1 / i = Num1 \ i Then
If InStr("*" & m_strPrimesM & "*", "*" & i & "*") > 0 Then Exit Function
Num1 = Num1 / i
End If
End If
Next i
IsHuZhi = True
End Function