Prime Factoring using a Visual Basic Module
How to perform prime factorization in Excel using a VBA module that loops through stored prime numbers to factor any whole number input.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Primes are the building blocks of whole numbers and play a critical role in cryptography, signal processing, music theory, quantum mechanics, and many other fields.
How the Module Works
The VBA module stores the first 100 prime numbers in a "Prime" worksheet. It uses two loops:
- FOR loop — iterates through the 100 primes one by one to find which can divide the input number. Terminates early once the number is fully factored to 1.
- DO loop — for each prime that divides the input, keeps dividing until the prime no longer divides evenly. This handles repeated prime factors (e.g., 1,500 = 2 × 2 × 3 × 5 × 5 × 5).
Sub Factoring()
Dim prime(1 To 100) As Integer, i As Integer
Dim InputNbr As Long
Sheets("Prime").Select
Range("A3").Select
For i = 1 To 100
prime(i) = ActiveCell.Value
ActiveCell.Offset(1, 0).Select
Next i
Sheets("Factoring").Select
InputNbr = Range("InputNbr").Value
Range("B5:B1000").Select
Selection.ClearContents
Range("B5").Select
For i = 1 To 100
If InputNbr = 1 Then
Exit For
End If
Do While InputNbr Mod prime(i) = 0
InputNbr = InputNbr / prime(i)
ActiveCell.Value = prime(i)
ActiveCell.Offset(1, 0).Select
Loop
Next i
If InputNbr > 1 Then
ActiveCell.Value = InputNbr
End If
End Sub
Usage
- Enter a whole number (no decimal places) in cell B3.
- Click the Go! button to run the module.
- The prime factors are listed starting from cell B5.
If the input number has no prime factors within the first 100 primes, the number itself appears as the result. If factoring requires primes beyond the first 100, the result may be incorrect — extend the prime list on the "Prime" worksheet to handle larger numbers.
The module currently processes one number at a time but can be extended with an additional loop to process a batch of inputs from a range.