Evaluate the number of all prime numbers within n

Source: Internet
Author: User
Private sub llstart_linkclicked (byval sender as system. Object, byval e _
System. Windows. Forms. linklabellinkclickedeventargs )_
Handles llstart. linkclicked
If isnumeric(me.txt maxnbr. Text) = false then
Msgbox ("Max NBR must be numeric! ",_
Msgboxstyle. Exclamation ,_
"Max NBR not numeric ")
Return
End if

Dim N, I, j
N = cint(me.txt maxnbr. Text)

Dim Z (N)
Dim starttime as datetime = now

'Initialize Array
For I = 0 to n
Z (I) = 0
Next

'Mark multiples of I

For I = 2 to n/2
For J = 2 * I to N step I
Z (j) = 1
Next
Next

'Count unmarked numbers, which are primes
Dim NBR = 0

For I = 2 to n
If Z (I) = 0 then
NBR + = 1
End if
Next

Dim TS as new timespan (now. ticks-starttime. ticks)


Me. lblnbrprimes. Text = NBR
Me. lbltime. Text = ts. tostring

End sub

Reply: this silly Code strengthened my confidence in VB. NET.

For I = 2 to n/2
For J = 2 * I to N step I
Z (j) = 1
Next
Next

This algorithm is used to traverse the number I from 2 to n/2. For each I, set all its multiples in array Z to 1. In fact, this Z can be expressed in the bool type. 1 is the sum, and 0 is the prime number.
For I = 2 to n
If Z (I) = 0 then
NBR + = 1
End if
Next
Traverse Z and NBR to write down the total number of prime numbers.
See the original algorithm: http://www.math.utah.edu/classes/216/assignment-07.html
This algorithm is indeed excellent. Its algorithm Z (j) = 1 indicates that the number of execution steps is X, and X indicates the number of all units smaller than N. Obviously, x <= n.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.