此代码为所有数字提供1的结果,我不知道为什么。对于此代码中的任何n,phi(n)给我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
答案 0 :(得分:1)
你将num1和num2传递给gcd,但没有对它们做任何事情。相反,你在那里使用a和b ...默认为零...因此gcd函数实际上没有做任何事情。即使它确实如此,你也没有告诉它根据它的结果返回任何东西。
答案 1 :(得分:1)
您的gcd
函数需要num1
和num2
并忽略它们,而是使用未初始化的a
和b
,因此为零。< / p>
答案 2 :(得分:1)
你在哪里设置gcd函数中变量a和b的值?我也没有看到你的gcd函数返回任何内容。
答案 3 :(得分:1)
您错过了Return
声明。
答案 4 :(得分:0)
使用两个文本框来表示数字。标签将包含GCD。这是Euclid算法的实现。
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