import java.util.Scanner;
public class Example1 {
public static void main(String[] args) {
//We will find the factorial of this number
int number;
System.out.println("Enter the number: ");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
scanner.close();
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
--------------------------------------------------------------------------------------------------------------------
Example2 :-
import java.math.BigInteger;
class Fact1
{
public static void main(String args[])
{
int n, c;
BigInteger inc = new BigInteger("1");
BigInteger fact = new BigInteger("1");
Scanner input = new Scanner(System.in);
System.out.println("Input an integer");
n = input.nextInt();
for (c = 1; c <= n; c++) {
fact = fact.multiply(inc);
inc = inc.add(BigInteger.ONE);
}
System.out.println(n + "! = " + fact);
}
}
Output:-
Input an integer
16
16! = 20922789888000
public class Example1 {
public static void main(String[] args) {
//We will find the factorial of this number
int number;
System.out.println("Enter the number: ");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
scanner.close();
long fact = 1;
int i = 1;
while(i<=number)
{
fact = fact * i;
i++;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Output:-
Enter the number:
5
Factorial of 5 is: 120
--------------------------------------------------------------------------------------------------------------------
Example2 :-
Above
program does not give correct result for calculating factorial of say 16.
Because 16! is a large number and can't be
stored in integer data type which is of 4 bytes.
To
calculate factorial of say hundred we use BigInteger class of java.math package.
import java.util.Scanner;import java.math.BigInteger;
class Fact1
{
public static void main(String args[])
{
int n, c;
BigInteger inc = new BigInteger("1");
BigInteger fact = new BigInteger("1");
Scanner input = new Scanner(System.in);
System.out.println("Input an integer");
n = input.nextInt();
for (c = 1; c <= n; c++) {
fact = fact.multiply(inc);
inc = inc.add(BigInteger.ONE);
}
System.out.println(n + "! = " + fact);
}
}
Output:-
Input an integer
16
16! = 20922789888000
0 comments:
Post a Comment