扩展的欧几里德代码的最终结果中的错误

时间:2010-11-20 19:20:09

标签: vb.net

这个应用程序通过使用扩展的欧几里德来计算gcd,但它只给我第一次迭代的值,但我需要x2的最终值y2 a

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim x1 As Integer
    Dim x2 As Integer
    Dim y1 As Integer
    Dim y2 As Integer
    Dim x As Integer
    Dim y As Integer
    Dim a As Integer
    Dim temp As Integer
    a = CInt(TextBox1.Text)
    Dim b As Integer
    b = CInt(TextBox2.Text)
    Dim q As Integer
    x1 = 0
    y1 = 1
    x2 = 1
    y2 = 0
    If b > a Then
        temp = a
        a = b
        b = temp
    End If
    Do While (b <> 0)
        q = Math.Floor(a / b)
        a = b
        b = a Mod b
        x = x2 - q * x1
        x2 = x1
        y = y2 - q * y1
        y2 = y1
        x1 = x
        y1 = y
    Loop


    MessageBox.Show("the final value of x2 is  " & CStr(x2) & "the final value of y2 is " & CStr(y2) & "the GCD is  " & CStr(a), " the result ")


End Sub

2 个答案:

答案 0 :(得分:1)

这是你的问题:

a = b
b =一个Mod b

在第二个语句中,a已经等于b,因此Mod b始终为零。

答案 1 :(得分:0)

    'Euclid's algorithm
    'code assumes that you are looking for the GCD of the
    'values entered into TextBox1 and TextBox2
    Dim dividend As Long
    Dim divisor As Long
    Dim quotient As Long
    Dim remainder As Long

    If Long.TryParse(TextBox1.Text, dividend) Then

        If Long.TryParse(TextBox2.Text, divisor) Then
            'place in correct order
            quotient = Math.Max(dividend, divisor) 'determine max number
            remainder = Math.Min(dividend, divisor) 'determine min number
            dividend = quotient 'max is dividend
            divisor = remainder 'min is divisor
            Do
                quotient = Math.DivRem(dividend, divisor, remainder) 'do the division
                'set up for next divide
                dividend = divisor 'dividend is previous divisor. if remainder is zero then dividend = GCD
                divisor = remainder 'divisor is previous remainder
            Loop While remainder <> 0 'loop until the remainder is zero
            Label1.Text = dividend.ToString("n0")
        End If
    End If