如果数字是总理或显示使用Excel公式的主要因素?

我在A列和B列中有整数,如果没有进一步的数字本身的因素,我想显示结果'总理'。 例如,如果数字是37,结果将是“总理”,如果它的44结果是2×2×11。 我怎样才能使用Excel公式做到这一点? 屏幕截图:

在这里输入图像说明

免责声明:下面的代码是从这个非常有用的VB.NET例子中移植过来的

Option Explicit Sub Test() Debug.Print FindFactors(2) Debug.Print FindFactors(3) Debug.Print FindFactors(11) Debug.Print FindFactors(12) Debug.Print FindFactors(13) Debug.Print FindFactors(16) Debug.Print FindFactors(17) Debug.Print FindFactors(24) Debug.Print FindFactors(25) Debug.Print FindFactors(11234) Debug.Print FindFactors(67894) End Sub Function FindFactors(lngNumber As Long) As String Dim collFactors As Collection Dim lngFactor As Long Dim lngCounter As Long Dim strFactors As String Dim strFactor As String Set collFactors = New Collection ' Take out the 2s. Do While (lngNumber Mod 2 = 0) collFactors.Add 2 lngNumber = lngNumber / 2 Loop ' Take out other primes. lngFactor = 3 Do While (lngFactor * lngFactor <= lngNumber) If (lngNumber Mod lngFactor = 0) Then ' This is a factor. collFactors.Add lngFactor lngNumber = lngNumber / lngFactor Else ' Go to the next odd number. lngFactor = lngFactor + 2 End If Loop ' If num is not 1, then whatever is left is prime. If lngNumber > 1 Then collFactors.Add lngNumber End If ' make a string out of collection strFactors = "" If collFactors.Count = 1 Then strFactors = "Prime" Else For lngCounter = 1 To collFactors.Count strFactors = strFactors & collFactors(lngCounter) If lngCounter < collFactors.Count Then strFactors = strFactors & "x" End If Next lngCounter End If FindFactors = strFactors End Function 

给出一个输出:

 Prime Prime Prime 2x2x3 Prime 2x2x2x2 Prime 2x2x2x3 5x5 2x41x137 2x83x409 

可以在工作表中使用:

在这里输入图像说明

这是一个简单的recursion版本。 这是基于这样一个想法,一旦你确定了一个因素,你把这个因素除以这个因素,然后把注意力转移到其余的因素上。

 Function Factor(ByVal n As Long, Optional FirstTrial As Long = 2) As String Dim i As Long Dim t As Long Dim limit As Long Dim rest As String Dim s As String If n = 1 Then Factor = n Exit Function End If limit = Int(Sqr(n)) t = FirstTrial Do While t <= limit If n Mod t = 0 Then rest = Factor(n / t, t) If rest <> "1" Then s = t & "x" & rest End If Factor = s Exit Function Else If t = 2 Then t = 3 Else t = t + 2 End If Loop 'if we get here: Factor = n End Function Function PrimeOrFactor(n As Long) As String Dim s As String s = Factor(n) If n = 1 Then PrimeOrFactor = "Neither" ElseIf (s) = Trim(n) Then PrimeOrFactor = "Prime" Else PrimeOrFactor = s End If End Function 

testing像:

 Sub test() Dim i As Long For i = 1 To 20 Cells(i, 1) = i Cells(i, 2) = PrimeOrFactor(i) Next i End Sub 

输出:

在这里输入图像说明