Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition.
Example:
Input lower limit: 9
Input upper limit: 20
Output:
10 = 3 + 7
12 = 5 + 7
14 = 3 + 11
16 = 3 + 13
18 = 5 + 13
20 = 3 + 17
1
Expert's answer
2012-08-30T09:53:34-0400
Module Module1
Sub Main() Dim lowerlimit As Integer Dim upperlimit As Integer Console.WriteLine("Input lower limit: ") lowerlimit = Integer.Parse(Console.ReadLine()) Console.WriteLine("Input upper limit: ") upperlimit = Integer.Parse(Console.ReadLine()) For i As Integer = lowerlimit To upperlimit If i Mod 2 = 0 Then Show(i) End If Next
Console.ReadLine() End Sub
Private Sub Show(ByVal number As Integer) Dim N As Integer = number Dim isprime(N) As Boolean For i As Integer = 2 To N - 1 isprime(i) = True Next For i As Integer = 2 To N If (i * i < N) Then If isprime(i) Then For j As Integer = i To N If i * j < N Then isprime(i * j) = False End If Next End If
End If Next Dim primes As Integer = 0
For i As Integer = 2 To N - 1 If isprime(i) Then primes = primes + 1
End If Next Dim list(primes) As Integer Dim nn As Integer = 0 For i As Integer = 0 To N - 1 If isprime(i) Then nn = nn + 1 list(nn) = i End If Next
Dim left As Integer = 0 Dim right As Integer = primes - 1
While left <= right If (list(left) + list(right) = N) Then Exit While ElseIf (list(left) + list(right) < N) Then left = left + 1 Else right = right - 1 End If
End While
If (list(left) + list(right) = N) Then Console.WriteLine(N.ToString() + " = " + list(left).ToString() + " + " + list(right).ToString()) Else Console.WriteLine(N.ToString() + " not expressible as sum of two primes") End If End Sub
Comments
Leave a comment