|
|
Title | Find a number's prime factors in Visual Basic 6 |
Description | This example shows how to find a number's prime factors in Visual Basic 6. |
Keywords | primes, prime numbers, prime factors, factors, factorization, Visual Basic 6, VB 6 |
Categories | Algorithms |
|
|
Once upon a time, I read an article where the author said something like this:
My professor asked us whether we had prime factored our Social Security numbers yet. Being a normal person, I laughed with everyone else. Being a nerd, I managed to resist for only three days.
Of course I immediately rushed to my computer and wrote a prime factoring program. At the time it was kind of hard because the computer I was using didn't have integers big enough to hold Social Security numbers. This is a lot easier now.
This example's FindFactors function finds a number's prime factors.
|
|
' Return the number's prime factors.
Private Function FindFactors(ByVal num As Long) As _
Collection
Dim result As New Collection
Dim factor As Long
' Take out the 2s.
Do While (num Mod 2 = 0)
result.Add 2
num = num \ 2
Loop
' Take out other primes.
factor = 3
Do While (factor * factor <= num)
If (num Mod factor = 0) Then
' This is a factor.
result.Add factor
num = num \ factor
Else
' Go to the next odd number.
factor = factor + 2
End If
Loop
' If num is not 1, then whatever is left is prime.
If (num > 1) Then result.Add num
Set FindFactors = result
End Function
|
|
|
|
|
|