Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: VB6
Expertise: Intermediate
Apr 14, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

GetPrimeNumbers - Evaluate the first N prime numbers

' Returns an array with the first N prime numbers
' Note: you can easily convert this routine to VB4 and VB5 by
' returning the result array through an argument instead of
' the return value

Function GetPrimeNumbers(numberOfPrimes As Long) As Long()
    Dim found As Long
    Dim n As Long
    Dim i As Long
    If numberOfPrimes <= 0 Then Err.Raise 1002, , "Invalid argument"
    ' we know the size of the result in advance
    ReDim result(1 To numberOfPrimes) As Long
    ' "2" is the first prime number
    result(1) = 2: found = 1
    n = 1
        ' all other prime numbers are odd, so we can skip even numbers
        n = n + 2
        ' let's check if N is a prime number
        For i = 1 To found
            If (n Mod result(i)) = 0 Then Exit For
        If i > found Then
            ' no prime number < N is a divisor for N
            ' therefore N is prime
            found = found + 1
            result(found) = n
            If found = numberOfPrimes Then Exit Do
        End If
    GetPrimeNumbers = result
End Function
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date