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

1 Answer

0 votes
/*
    This program computes the factorial of numbers greater than 20.
    Scala's BigInt type automatically expands to arbitrary size,
    making it ideal for very large factorials.
*/

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

  for (i <- BigInt(2) to n) {
    result *= i
  }

  result
}

/*
    Main entry point: read input, compute factorial, print result.
*/
object BigFactorial extends App {
  print("Enter a number greater than 20: ")
  val n: BigInt = BigInt(scala.io.StdIn.readLine().trim)

  val result: BigInt = factorialBig(n)

  println(s"\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

...