找到最大公约数的方法是什么?

时间:2014-03-17 21:42:42

标签: vb.net

如何找到3个Textboxes值的最大公约数,并在第四个Textbox中使它成为apper?

Public Class Form1
    Dim a As Integer
    Dim b As Integer
    Dim c As Integer
    Dim d As Integer

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        a = Val(TextBox1.Text)
        b = Val(TextBox2.Text)
        c = Val(TextBox3.Text)
        d = Val(TextBox4.Text)

        -------------------------   Val(TextBox4.Text) = ----------------

    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

首先,您需要为最大公分母设置最高的最小值:

Dim minimum As Integer If a <= b And a <= c minimum = a Else If b <= a And a <= c minimum = b Else If c <= a And a <= b minimum = c End If

使用for循环和Mod方程式如下:

For i As Integer = minimum To 1 Step -1 If a Mod i = 0 And b Mod i = 0 And c Mod i = 0 Return i End If Next

这会将最小数字设置为变量最小值并倒数,直到我没有a,b和c的余数,从而产生最大的公分母。