Search code examples
excelvbarecursion

Simple recursive function in VBA with Excel not returning expected result


I have a simple recursive function to write in VBA that does the following : It must count the number of times we must take the log of a parameter 'x' to find log(x) < 1

Examples :

  • logcount(5) : log(5) = 0,6... so the function should return 1
  • logcount(89) : log(89) = 1,9... and log(log(89)) = 0,28... so the function should return 2
  • logcount(0,4) should return 1 etc...

So I wrote it and it doesn't work as expected ! It always adds +1 to the result ! It looks like the last 'Else' block is always interpreted. Any help will be really appreciated

Function logcount(x As Double) As Integer
  If x <= 0 Then
    MsgBox "You must enter a positive value"
    Exit Function
  ElseIf Log(x) < 1 Then
    logcount = 1
  Else
    logcount = 1 + logcount(Log(x))
  End If
End Function

Solution

  • Log in VBA is the natural logarithm.

    Apparently you meant a base-10 logarithm:

    Log10 = Log(X) / Log(10#)