View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.worksheet.functions
Gord Dibben
 
Posts: n/a
Default how do I find prime factors of a number

Grabbed this code from one of these news groups. Wish I could attribute, but
can't remember.

Run on new worksheet or one with nothing in Column A

Sub Listfactors()
Range("A1").Select
Dim Originalnumber As Long
Dim Factors() As Integer
Dim Counter As Integer
Dim Fact As Integer
Dim theRest As Long
Dim Formulastring As String

Originalnumber = CLng(Val(InputBox("Number:")))
theRest = Originalnumber
Counter = 0
ReDim Factors(0)
For Fact = 2 To Originalnumber
If theRest / Fact = Int(theRest / Fact) Then
ReDim Preserve Factors(Counter)
Factors(Counter) = Fact
Counter = Counter + 1
theRest = theRest / Fact
Fact = Fact - 1
End If
Next
Formulastring = "="
For Counter = LBound(Factors) To UBound(Factors)
Cells(Counter + 1, 1).Value = Factors(Counter)
Formulastring = Formulastring & _
Cells(Counter + 1, 1).Address & "*"
Next
Formulastring = Left(Formulastring, Len(Formulastring) - 1)
Cells(UBound(Factors) + 2, 1).Formula = Formulastring
End Sub


Gord Dibben Excel MVP

On 28 Nov 2005 20:37:04 -0800, "DOR" wrote:

The method I provided finds the *factors* of N, not the prime factors,
and only up to an N of 65,536 at that, unless you are willing to forego
N itself, in which case it can be modified to go higher, to 131,072.
Sorry about that, I didn't read your post properly. You can find a
method of finding factors here

http://tinyurl.com/dljjt

using VBA. This also has a macro for finding the primes up to a given
number. You may be able to combine the two methods to get the prime
factors.

FWIW, there is a program available here

http://tinyurl.com/aleae

for computing prime factors.

I hope THIS helps, as opposed to my previous post.

I'll take another look at it to see if I can find or determine another
approach.

Declan O'R