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
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.