VB求两个数的最大公约数和最小公倍数

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/23 19:09:02

VB求两个数的最大公约数和最小公倍数
VB求两个数的最大公约数和最小公倍数

VB求两个数的最大公约数和最小公倍数
Private Sub Command1_Click() 
    Dim S As Long 
    S = YueOrBei(24, 32) 
    MsgBox "24 和 32 的最大公约数是:" & S, vbInformation 
    S = YueOrBei(24, 32, True) 
    MsgBox "24 和 32 的最小公倍数是:" & S, vbInformation 
End Sub 
Private Function YueOrBei(J1 As Long, J2 As Long, Optional IsBei As Boolean) As Long     'IsBei=True 返回公倍数(最小),否则返回公约数(最大) 
    Dim S As Long, S1 As Long, S2 As Long 
    S1 = J1: S2 = J2 
    Do 
    S = S1 Mod S2 
    If S = 0 Then YueOrBei = S2: Exit Do 
    S1 = S2: S2 = S 
    Loop 
    If IsBei Then YueOrBei = J1 * J2 / YueOrBei 
End Function

另一种方法

Private Sub Form_Click() 
    m1 = InputBox("输入m") 
    n1 = InputBox("输入n") 
    If m1 > n1 Then '为了求最小公倍数,增加m,n变量 
    m = m1: n = n1 
    Else 
    m = n1: n = m1 
    End If 'm>n 
    r = m Mod n 
    Do While r <> 0 
    m = n 
    n = r 
    r = m Mod n 
    Loop 
    Print m1; ","; n1; "的最大约数为"; n 
    Print "最小公倍数=", m1 * n1 / n 
End Sub