The Greatest Programmers of Our Time-Ever


/**

* The Factorial program implements an application that

* calculates the factorial of a number and prints

* it to standard output.

*

* @author Seeta (seetadev@gmail.com)

* @version 1.0

*/

public class Factorial {

public static void main(String[] args) {

int num = 5;

long factorial = 1;

for(int i = 1; i <= num; ++i) { // factorial = factorial * i; factorial *= i; } System.out.printf("Factorial of %d = %d", num, factorial); } } A factorial program in java is a program that takes an integer as input, and computes the factorial of that integer. For example, if the input is 5, the factorial output will be 1*2*3*4*5 = 120 In mathematics, the notation 5! stands for 1*2*3*4*5. So here is the Java program to compute factorial of an integer number. public class Factorial { public static void main(String[] args) { int num = 5; long factorial = 1; for(int i = 1; i <= num; ++i) { factorial *= i; } System.out.printf("Factorial of %d = %d", num, factorial); } } import java.math.BigInteger; import java.util.*; public class Factorial { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); System.out.println("The factorial of " + n + " is " + factorial(n)); } public static BigInteger factorial(int n) { BigInteger f = new BigInteger("1"); // Or BigInteger.ONE for (int i = 2; i <= n; i++) f = f.multiply(BigInteger.valueOf(i)); return f; } } public class Main { public static void main(String[] args) { int number = 5, fact = 1; for (int i = 1; i <= number; i++) { fact = fact * i; } System.out.println("Factorial: " + fact); } } The Factorial Program in Java is a very famous program to find out the factorial of a given number. Factorial of any number n is denoted as n! and is equal to 1*2*3*....*(n-1)*n. For example, 4! = 4*3*2*1 = 24. Factorial of any number is always positive and always appears to be an integer and not a floating point number. For example, factorial of 3.5 should not exist and the factorial of a negative number does not exist too. But what about 0! ? Before we move on to the factorial program in Java, let us see what actually happens when we say find factorial of 10 or 5. 5! = 5 * 4 * 3 * 2 * 1 = 120 10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 3628800 import java.math.BigInteger; public class Factorial { public static void main(String[] args) { System.out.println(factorial(100)); } public static BigInteger factorial(int n) { BigInteger result = BigInteger.ONE; for (int i = 2; i <= n; i++) result = result.multiply(BigInteger.valueOf(i)); return result; } } public class factorial { public static void main(String[] args) { int i,fact=1; int number=5;//It is the number to calculate factorial for(i=1;i<=number;i++) { fact=fact*i; } System.out.println("Factorial of "+number+" is: "+fact); } }


Leave a Reply

Your email address will not be published. Required fields are marked *