How to compute the factorial of a number greater than 20 in Kotlin

1 Answer

0 votes
import java.math.BigInteger

/*
    This program computes the factorial of numbers greater than 20.
    Kotlin uses Java's BigInteger for arbitrary‑precision arithmetic,
    allowing us to safely compute extremely large factorials.
*/

/*
    Compute factorial using BigInteger.
    The algorithm multiplies numbers from 2 to n.
    BigInteger handles overflow internally and grows as needed.
*/
fun factorialBig(n: Int): BigInteger {
    var result: BigInteger = BigInteger.ONE

    for (i in 2..n) {
        result = result.multiply(BigInteger.valueOf(i.toLong()))
    }

    return result
}

/*
    Main entry point: read input, compute factorial, print result.
*/
fun main() {
    print("Enter a number greater than 20: ")
    val n: Int = readLine()?.trim()?.toIntOrNull() ?: 0

    val result: BigInteger = factorialBig(n)

    println("\nFactorial of $n is:\n")
    println(result)
}


/*
run:

Enter a number greater than 20: 25
Factorial of 25 is:

15511210043330985984000000

*/

 



answered Sep 14 by avibootz

Related questions

...