Yesterday I wrote an article for an Excel function, checking whether a specified number is prime or not.

Today I tought that it would be somehow a good idea to modify this function, in a way to check the number and if it is not prime to write down the divisors. Actually it was not very tough, as far as I have changed only a few lines of the code, making it a lot slower by removing the square root from the previous calculation. Anyway, the speed is not an issue, so enjoy the result from the routine “TestPrimeNumbers()” here:

The way the function works can be viewed here:

And finally the code. Find the 10 differences with the one from yesterday :

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
Option Explicit Public Const cPrime As String = "Prime" Public Const cNotPrime As String = "Not a prime, has other divisors." Public Const cNotPositive As String = "A number should be an integer bigger than 0." Public Function fDivisors(lNumber) As String Dim i As Long Dim bFirst As Boolean If (lNumber = 1) Or (lNumber = 2) Or (lNumber = 3) Then fDivisors = cPrime Exit Function End If If (lNumber < 1) Or (lNumber <> CLng(lNumber)) Then fDivisors = cNotPositive Exit Function End If For i = 2 To (lNumber + 1) / 2 Step 1 If lNumber Mod i = 0 Then If Not bFirst Then fDivisors = i Else fDivisors = fDivisors & ", " & i End If bFirst = True End If Next i If Len(fDivisors) < 1 Then fDivisors = cPrime End Function Public Sub TestPrimeNumbers(lStart As Long, lEnd As Long) Dim i As Long For i = lStart To lEnd Step 1 Debug.Print i & " " & fDivisors(i) Next i End Sub |

Enjoy it! 🙂