Prime numbers in array

mary13

Newcomer
Joined
Nov 18, 2003
Messages
3
Location
Australia, from Minnesota
I am working on some array exercises and need to be able to find all the primes out of a file of numbers, but I don't know how to write code for determining whether or not a number is prime.
Mary
 
How about something like this:

Visual Basic:
blnIsPrime = True
For count = 2 To (currentNumber / 2)
      If (currentNumber Mod count) = 0 Then
            blnIsPrime = False
      End If
Next count

This code uses the modulus operator to determine if there is a number (other than 1 or the number it is checking) that divides evenly into the number you are checking. If there is, then it is a not a prime number, and it changes the boolean to False. I'm not sure, but I think that 2 might also be a prime number. If it is a prime number, you will have to add an If statement to check if the number is two. If it is 2, it should change the boolean to True.
 
You could speed that up by checking if it is divisible by 2 and then only checking the odd numbers.
Also you could issue an Exit For if the number is prime and avoid testing all the numbers after the match has been found.
 
When checking for prime you only need to check to the sqrt of the possible prime. This will speed up the testing even more. The time you save increases rapidly when testing large numbers.

Visual Basic:
For count = 2 to Sqrt(currentNumber)
      ...
Next
Take for example the number 1000000. Testing up to sqrt of the number will be 500 times faster then testing up to half the number.
(1000000/2)/Sqrt(1000000)=500.
 
Back
Top