Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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

Posted

How about something like this:

 

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.

Take a look at my programs. Go to my web site.
Posted

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.

 

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.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...