EXCEL高手用VBA计算两个数的最大公约数用短除法
发布网友
发布时间:2022-08-07 02:04
我来回答
共1个回答
热心网友
时间:2024-10-31 15:42
Sub *()
Dim a(), b()
m = InputBox("输入第一个自然数")
n = InputBox("输入第二个自然数")
If m > n Then
t = m
m = n
n = t
End If
ReDim a(1)
a(1) = 2
k = 1
For i = 3 To m Step 2
If ss(i) Then
k = k + 1
ReDim Preserve a(k)
a(k) = i
End If
Next
ReDim b(1)
b(1) = 1
i = 1
k = 1
Do While a(i) <= m
If m Mod a(i) = 0 And n Mod a(i) = 0 Then
k = k + 1
ReDim Preserve b(k)
b(k) = a(i)
m = m / a(i)
n = n / a(i)
Else
i = i + 1
End If
Loop
n = 1
For i = 1 To k
n = n * b(i)
Next
MsgBox ("最大公约数为" & n)
End Sub
Function ss(ByVal x)
ss = True
For i = 3 To Sqr(x) Step 2
If x Mod i = 0 Then ss = False: Exit For
Next
End Function
追问好高手