[Originally posted by drop]
how can I get the prime factors of a number?
Printable View
[Originally posted by drop]
how can I get the prime factors of a number?
[Originally posted by Mikekay2]
The following code shows an easy to follow method:
Dim Factors() As Long
Dim Pointer As Long
Private Sub Command1_Click()
Dim I as Integer
Pointer=0
For I = LBound(Factors) To UBound(Factors)
ÿ ÿ Factors(I) = 0
Next
' set number to be the number you want to factorise
While Not GetFactors(Number)
Wend
' pointer -1 gives no of factors
For I = 1 To Pointer - 1
ÿ 'Factors(i) will give each prime factor in turn
Next
End Sub
Public Function GetFactors(ByRef ToFactorise As Long) As Boolean
Dim I As Long
ÿ ÿ For I = 2 To ToFactorise
ÿ ÿ ÿ ÿ If ToFactorise Mod I = 0 Then
ÿ ÿ ÿ ÿ ÿ ÿ If IsPrime(I) Then
ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ Factors(Pointer) = I
ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ Pointer = Pointer + 1
ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ ToFactorise = ToFactorise / I
ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ GetFactors = False
ÿ ÿ ÿ ÿ ÿ ÿ ÿ ÿ Exit Function
ÿ ÿ ÿ ÿ ÿ ÿ End If
ÿ ÿ ÿ ÿ ÿ ÿ
ÿ ÿ ÿ ÿ End If
ÿ ÿ Next
ÿ ÿ
ÿ ÿ GetFactors = True
ÿ ÿ
End Function
Public Function IsPrime(NumberToCheck As Long) As Boolean
Dim I As Long
ÿ ÿ For I = 2 To NumberToCheck / 2
ÿ ÿ ÿ ÿ If NumberToCheck Mod I = 0 Then
ÿ ÿ ÿ ÿ ÿ ÿ IsPrime = False
ÿ ÿ ÿ ÿ ÿ ÿ Exit Function
ÿ ÿ ÿ ÿ End If
ÿ ÿ Next
ÿ ÿ
ÿ ÿ IsPrime = True
ÿ ÿ
End Function