VBA 自订函数 -- 分解质因子
最大解 15位数,以上则无能为力。
继承13楼思路,除了开方也撇开偶数。
Function Factorize(ByVal src) As String
Dim num#, tnum#, i#, output$
num = src
If num < 2 Or num <> Int(num) Then
Factorize = "限>=2正整数": Exit Function
ElseIf num > 10 ^ 15 Then
Factorize = "限15位数以内": Exit Function
End If
Do While num / 2 = Int(num / 2)
num = num / 2
output = output & " * 2"
Loop
Dim loopend: loopend = Int(num ^ 0.5 + 1)
For i = 3 To loopend Step 2
encore:
tnum = num / i
If tnum = Int(tnum) Then
num = tnum
output = output & " * " & i
If i > num ^ 0.5 + 1 Then Exit For
GoTo encore
End If
Next
If num > 1 Then output = output & " * " & num
output = Mid(output, 4, 1000)
If output = src Then output = output & " =质数"
Factorize = output
End Function