Oorang
Well-known Member
- Joined
- Mar 4, 2005
- Messages
- 2,071
I poseted this over at the lounge because it is more something I was tinkering with for fun. I wass helping a friend with her homework and she had to do a program to output prime numbers. The first solution that came to mind was a simple brute force approach. But the more I got thinkg about it the deeper I realized the problem went. You don't ever need to test even numbers past and I found someone elses solution showing how you could avoiding testing multiples of 3 by alternating your increment by 2 and 4 in turn. Then it occured to me I didn't need to test WITH any number other than a prime number. And I only need to test up to the square root of the number being tested. However it still feels like this could be done better. I was wondering if anyone could take a peek at what I have and lend any thoughts on how to speed it up?
Code:
Option Explicit
Sub OuputPrime()
Dim TestedNumber As Double
Dim TestingLimit As Double
Dim LoopCount As Double
Dim PrimeArray() As Double
Dim IsPrime As Boolean
Dim Increment As Byte
Dim T As Date
On Error GoTo exitlight
T = Time
On Error Resume Next
TestingLimit = InputBox("Find primes up to what number?", "Prime List", 1E+16)
If TestingLimit = 0 Then Exit Sub
ReDim PrimeArray(1)
PrimeArray(0) = 2
PrimeArray(1) = 2
Range("a1") = 2
Range("a2") = 3
TestedNumber = 5
Do Until TestedNumber > TestingLimit
If Increment = 2 Then Increment = 4 Else: Increment = 2
IsPrime = True
For LoopCount = LBound(PrimeArray) To UBound(PrimeArray)
If PrimeArray(LoopCount) > Int(Sqr(TestedNumber)) Then Exit For
If TestedNumber Mod PrimeArray(LoopCount) = 0 Then
IsPrime = False
Exit For
End If
Next LoopCount
If IsPrime = True Then
ReDim Preserve PrimeArray(UBound(PrimeArray) + 1)
PrimeArray(UBound(PrimeArray)) = TestedNumber
ActiveSheet.Cells(UBound(PrimeArray) + 1, 1) = TestedNumber
End If
TestedNumber = TestedNumber + Increment
Loop
exitlight:
End Sub