Private Sub command1_click()
Dim p As Integer
Dim q As Integer
Dim temp As Integer
Dim r As Integer
p = Val(Text1.Text)
q = Val(Text2.Text)
If p <q Then
temp = p
p = q
q = temp
End If
Do
r = p Mod q
If r = 0 Then
MsgBox Str(q) &"为公约数"
Exit Do
Else
p = q
q = r
End If
Loop
End Sub
解析:欧几里德求公约数算法:
步骤1:如果p<q,则交换p和q.
步骤2:令r是p/q的余数.
步骤3:如果r=0,则q为最大公约数否则令p=q,q=r并转入步骤2.
我以前做练习存下来的,最大公约数的两个高效算法:第一个,更相减损术:
Private Sub Command1_Click() '更相减损术
Dim k%, a%, b%, c%
a = Val(Text1)
b = Val(Text2)
If (a Mod 2 = 0) And (b Mod 2 = 0) Then
a = a \ 2
b = b \ 2
k = 2
Else
k = 1
End If
If a <b Then
t = a
a = b
b = t
End If
Do
c = a - b
If c >b Then
t = a
a = b
b = t
End If
a = b
b = c
Loop Until a = b
b = b * k
If b = 1 Then
Label1 = "这两个数"
Label1 = b
End Sub
第二个,欧几里德算法(辗转相除法),这个很简单,你百度一下就好了,这里就不写了。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)