- To print factorial of a number
User Input: 5
Output:
Factorial of 5 : 120
import java.util.Scanner
fun main(args: Array<String>) {
Scanner userInput = Scanner(System.`in`)
print("Enter your last number : ")
var num:Int = userInput.nextInt()
var fact:Long = 1
for (i in 1..num)
fact*=i
System.out.print("Factorial of $num : $fact")
}
Enter your number : 3 Factorial of 3 : 6Program
You should know first :
Factorial of N : 1*2*3*4.....*N
Factorial of 0 : 1
The variable which holds factorial value (above fact
) must be of type long
Because,
long : Factorial of a number can be very large [ valid for upto 20! ]
for (i in 1..num)
fact*=i
For greater than 20! , you have to use BigInteger of java Math library
Must import java.math.BigInteger in this case
for (i in 1..num.toLong())
fact = fact.multiply(BigInteger.valueOf(i);
Concept