mary13 Posted November 18, 2003 Posted November 18, 2003 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 Quote
Klogg Posted November 18, 2003 Posted November 18, 2003 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. Quote Take a look at my programs. Go to my web site.
Administrators PlausiblyDamp Posted November 18, 2003 Administrators Posted November 18, 2003 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
themster Posted November 20, 2003 Posted November 20, 2003 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. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.