2010-11-20 65 views
0

此應用程序的計算,通過使用擴展的歐幾里德,但它給我只是第一次迭代的價值,但我需要X2 Y2的最終值錯誤的擴展歐幾里德代碼

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 

回答

1

下面是GCD的最終結果你的問題:

A = b
b = A國防部b

在第二份聲明,一個是已經等於b,所以國防部b爲始終爲零。

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