Kotlin Program to Find Factorial of a number

Kotlin Server Side ProgrammingProgramming

In this article, we will understand how to find the factorial of a number. Factorial of a number is the product of itself with each of its lower numbers.

Below is a demonstration of the same −

Suppose our input is

Enter the number : 5

The desired output would be −

The factorial of 5 is 120

Algorithm

  • Step 1 − Start

  • Step 2 − Declare three integers: input, myResult and i

  • Step 3 − Hardcode the integer

  • Step 4 − Run a for-loop, multiply the number with its lower number and run the loop till the number is reduced to 1.

  • Step 5 − Display the result

  • Step 6 − Stop

Example 1

In this example, we will calculate the factorial of a number in Kotlin using for loop. First, declare and set the input for which we will find the factorial later −

val input = 5

Set a variable wherein the factorial result will be displayed

var myResult: Long = 1

Now, use the for loop to calculate the Factorial:

for (i in 1..input) { myResult *= i.toLong() }

Let us now see the complete example to calculate the Factorial of an integer −

fun main() { val input = 5 println("The input value is defined as $input") var myResult: Long = 1 for (i in 1..input) { myResult *= i.toLong() } println("The factorial of $input is $myResult") }

Output

The input value is defined as 10
The factorial of 10 is 120

Example 2

In this example, we will calculate the factorial of a number in Kotlin

fun main() { val input = 5 println("The input value is defined as $input") printFactors(input) } fun printFactors(input: Int) { var myResult: Long = 1 for (i in 1..input) { myResult *= i.toLong() } println("The factorial of $input is $myResult") }

Output

The number is 5
The factorial of 5 is 120

Example 3

In this example, we will calculate the factorial of a number using Recursion in Kotlin −

fun main() { val input = 7 val res: Long println("The input value is defined as $input") res = factorialFunc(input) println("
Factorial = $res"
) } fun factorialFunc(input: Int): Long { return if (input == 1) input.toLong() else input*factorialFunc(input-1) }

Output

The input value is defined as 7
Factorial = 5040
raja
Updated on 13-Oct-2022 12:51:24

Advertisements