Answer to Question #14040 in Visual Basic for Angela Cadampog

Question #14040
how to Create programs that, given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.
1
Expert's answer
2012-09-06T10:01:20-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


End Module

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS