Recursive factorial in Kotlin

problem

Let’s calculate the factorial of a given number n using a recursive approach. Recall the mathematical formula of factorial:

n! = n × (n – 1)!

SOLUTION

				
					fun fact(n:Int):Long = if (n==0) 1 else n * fact(n-1)
				
			
running

To run the above we can call it from the main function. Putting all code in one file will look like below:

factorial.kt
				
					fun main() {
    print (fact(5))
}

fun fact(n:Int):Long = if (n==0) 1 else n * fact(n-1)
				
			

Save the code file above as factorial.kt. Now to compile in your terminal:

				
					kotlinc factorial.kt
				
			

After successful compilation, you should have FactorialKt.class at the current directory. Run it by:

				
					kotlin FactorialKt
				
			
output

The output should be 120

Correct!

SOLUTION WITH BIG NUMBERS (BIGINTEGER)

The above code assumes that no negative number will be given. Also, it has a downside if the input number is bigger than 20! It will overflow the Long type as it will reach its limit. That can be fixed by replacing the Long type to BigInteger. For instance:

factorial.kt
				
					fun fact(n:BigInteger):BigInteger = if (n.compareTo(BigInteger.valueOf(1))<=0) BigInteger.valueOf(1) else fact(n.dec()).times(n)
				
			

In order to multiply a BigInteger object one has to use the times() method instead of the * operator. Also in order to decremement by one, the method dec() is used. And finally the valueOf() creates a BigInteger object with the given value so the main method is also changed. The full code is as below, including an update to the main function for more user friendly output:

factorial.kt
				
					import java.math.BigInteger;
 fun main() {
     println("5! = " + fact(BigInteger.valueOf(5)))
     println("0! = " + fact(BigInteger.valueOf(0)))
     println("1! = " + fact(BigInteger.valueOf(1)))
     println("50! = " + fact(BigInteger.valueOf(50)))
     println("100! = " + fact(BigInteger.valueOf(100)))
 }
 fun fact(n:BigInteger):BigInteger = if (n.compareTo(BigInteger.valueOf(1))<=0)  BigInteger.valueOf(1) else fact(n.dec()).times(n)
				
			
output with big numbers
				
					5! = 120
0! = 1
1! = 1
50! = 30414093201713378043612608166064768844377641568960512000000000000
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
				
			

conclusion

That was one way of implementing factorial in a recursive manner using Kotlin. Another one way would be to use a tail-recursive approach.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x