Factorial function returning squared number and not factorial

Viewed 252

Where is my code wrong? It is returning the square of any number:

Sub factorial()
Dim x As Long, i As Integer, fact As Long
   x = InputBox("enter the integer")
   For i = 1 To x
      fact = i * x
      Next i
   MsgBox fact
End Sub 
3 Answers

Practicing Loops and If Statements!?

Option Explicit

' If you are practicing (loops) then:
Sub factorial()
    Dim x As Long, i As Long, fct As Double
    x = InputBox("enter the integer")
    If x >= 0 And x <= 170 Then
        fct = 1
        If x > 1 Then
            For i = 2 To x
                fct = fct * i
            Next i
        End If
        MsgBox fct
    Else
        MsgBox "Next time enter a number between 0 and 170."
        Exit Sub
    End If
End Sub

' ...if not, just use Fact
Sub factorialExcel()
    Dim x As Long
    x = InputBox("enter the integer")
    If x >= 0 And x <= 170 Then
        MsgBox Application.WorksheetFunction.Fact(x)
    Else
        MsgBox "Next time enter a number between 0 and 170."
        Exit Sub
    End If
End Sub

One mistake is that fact needs to be initialized with fact=1 before it is used in the loop. Then inside the loop the result is should be multiplied by the iteration number, as in fact = fact * i. Lastly to make sure you get the highest possible range use the LongLong type (available in VB7 and above) which is a 64-bit integer. Oh, and don't forget to convert the text returned by InputBox to a number type.

Sub factorial()
Dim x As Long, i As Long, fact As LongLong
   x = CLng(InputBox("enter the integer"))
   fact = 1
   For i = 1 To x
      fact = fact * i
   Next i
   MsgBox fact
End Sub 

PS. Never use Integer in VBA, but rather opt for the native 32-bit integer Long.

In your code the value of fact is recalculated on any iteration and it is not kept. So at the end, just the last value is shown, which is x*i where i=x, e.g. a square of the input. Something like this, using 90% of your code works:

Sub Factorial()

    Dim x As Long, i As Long, fact As Long
    x = 5
    fact = 1
    For i = 1 To x
        fact = fact * i
    Next i
    
    Debug.Print fact
    
End Sub
Related