Kotlin program to find factorial of a number

Kotlin | Factorial of a number: Here, we are going to learn how to find the factorial of a given number in Kotlin? Submitted by IncludeHelp, on April 16, 2020

Factorial of number is the product of all positive numbers less or equal to the number.

Factorial of number n is denoted by n! is calculated using the formula, n! = n*(n-1)*(n-2)*...*2*1.

Kotlin - Find factorial of a number

To find the factorial of the entered number, we have used a for loop that runs from n to 1. At each iteration, i is multiplied with the factorial variable.

Example:

Input: 
n = 5

Output:
factorial = 120 [5x4x3x2x1 = 120]

Program to find factorial of a number in Kotlin

package com.includehelp.basic

import java.util.*

// Main Method Entry Point of Program
fun main(args:Array<String>) {
    // InputStream to get Input
    var reader = Scanner(System.`in`)
    
    // Input Integer Value
    println("Enter Number : ")
    var number = reader.nextInt()
    
    var factorial: Long=1
    
    for(i in 1..number){
        // Calculate Factorial
        factorial*=i.toLong()
    }
    
    // printing
    println("Factorial of $number is $factorial ")
}

Output

Run1 :
Enter Number :
5
Factorial of 5 is 120
---
Run 2:
Enter Number :
12
Factorial of 12 is 479001600

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.