当前位置: 动力学知识库 > 问答 > 编程问答 >

vb.net - error calculating common denominators

问题描述:

This code gives a result of 1 for all numbers and i don't know why. phi(n) for any n in this code give me 1.

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim n As Integer

n = CStr(TextBox1.Text)

Dim phi As Integer

Dim i As Integer

phi = 1

For i = 1 To n

If (gcd(i, n) = 1) Then

phi = phi + 1

End If

Next

Label3.Text = phi

End Sub

Private Function gcd(ByVal num1 As Integer, ByVal num2 As Integer) As Integer

Dim a As Integer

Dim b As Integer

Dim reminder As Integer

Dim temp As Long

If (b > a) Then

temp = a

a = b

b = temp

End If

Do While (b <> 0)

reminder = a Mod b

a = b

b = reminder

Loop

End Function

网友答案:

You're passing num1 and num2 to gcd, but not doing anything with them. Instead you're using a and b in there...which will default to zero...therefore the gcd function doesn't actually do anything. And even if it did, you've not told it to return anything based on the results of it.

网友答案:

Your gcd function takes num1 and num2 and ignores them, working instead with a and b which are not initialized and so are zero.

网友答案:

Where do you set the value of the variables a and b in the gcd function? I also don't see your gcd function returning anything.

网友答案:

You're missing a Return statement.

网友答案:

Use two textboxes to represent the numbers. The label will contain the GCD. This is an implementation of Euclid's algorithm.

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: