Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleFind a number's prime factors in Visual Basic .NET
DescriptionThis example shows how to find a number's prime factors in Visual Basic .NET.
Keywordsprimes, prime numbers, prime factors, factors, factorization, Visual Basic .NET, VB.NET
CategoriesAlgorithms
 
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 List(Of _
    Long)
    Dim result As List(Of Long) = New List(Of Long)()

    ' Take out the 2s.
    Do While (num Mod 2 = 0)
        result.Add(2)
        num \= 2
    Loop

    ' Take out other primes.
    Dim factor As Long = 3
    Do While (factor * factor <= num)
        If (num Mod factor = 0) Then
            ' This is a factor.
            result.Add(factor)
            num \= factor
        Else
            ' Go to the next odd number.
            factor += 2
        End If
    Loop

    ' If num is not 1, then whatever is left is prime.
    If (num > 1) Then result.Add(num)

    Return result
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated