注册 登录
编程论坛 VB.NET论坛

VB.net 双重循环问题

aliceabcd 发布于 2017-06-16 16:04, 2613 次点击
验证哥德巴赫猜想:任意一个大于等于6的偶数都可以分解为两个质数之和。
基本思想:n为大于等于6的任一偶数,可分解为n1和n2两个数,
分别检查n1和n2是否为素数,如都是,则为一组解。
如n1不是素数,就不必再检查n2是否素数。先从n1=3开始,
检验n1和n2(n2=N-n1)是否素数。然后使n1+2
再检验n1、n2是否素数,… 直到n1=n/2为止。
我的代码:
 Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Label2.Text = ""
        Dim a, n, i, j, k, fir, sec As Integer, flag, fla As Boolean
        a = Val(TextBox1.Text)
        For n = 3 To a / 2 Step 2
            flag = True
            For i = 2 To (n - 1)
                If n Mod i = 0 Then
                    flag = False : Exit For
                End If
            Next i
            If flag Then
                fir = n
                sec = a - n
                For k = 3 To sec / 2 Step 2
                    fla = True
                    For j = 2 To (k - 1)
                        If n Mod j = 0 Then
                            fla = False : Exit For
                        End If
                    Next j
                    If fla Then
                        Label2.Text += a.ToString + "=" + fir.ToString + "+" + sec.ToString + Chr(10)
                    ElseIf fla = False Then
                        Exit For
                    End If
                Next k
            ElseIf flag = False Then
                Exit For
            End If
        Next n
    End Sub
End Class
结果出来的不对,一样的结果出来好几遍,求大神帮改!!!
4 回复
#2
aliceabcd2017-06-16 16:11
#3
zjygwx2017-07-09 21:30
思想好象就不对,从3开始加2的数不一定是质数,比如9
#4
xyxcc1772017-07-18 18:06
Private Function IsPrimeNumber(ByVal intvalue As Integer) As Boolean
        Dim i As Integer
        For i = 3 To intvalue - 1 Step 2
            If intvalue Mod i = 0 Then
                IsPrimeNumber = False
                Return IsPrimeNumber
            End If
        Next
        Return True
    End Function

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim a As Integer = Val(TextBox1.Text)
        Dim flag1 As Boolean : Dim flag2 As Boolean
        Dim k As Integer
        For k = 3 To a - 3
            flag1 = IsPrimeNumber(k)
            flag2 = IsPrimeNumber(a - k)
            If flag1 And flag2 Then
                Label1.Text = "a=" & k.ToString & "+" & (a - k).ToString
            End If
        Next
    End Sub
#5
xyxcc1772017-07-18 18:08
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim a As Integer = Val(TextBox1.Text)
        Dim flag1 As Boolean : Dim flag2 As Boolean
        Dim k As Integer
        For k = 3 To a - 3
            flag1 = IsPrimeNumber(k)
            flag2 = IsPrimeNumber(a - k)
            If flag1 And flag2 Then
                Label1.Text = "a=" & k.ToString & "+" & (a - k).ToString
                Exit sub
            End If
        Next
    End Sub
1