how to find factorial in java
In this article, we will learn how to find the factorial of a number in java. The factorial of a number is the product of all the integers from 1 to that number.
Factorial of a non-negative integer, is multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
We will implement 5 Different Ways to find the factorial number in java.
E.g:
- Java Program Using For Loop
- Using Command Line Arguments
- Using Function
- Using Recursion
- Using while loop
Example 1:
Java Program To Calculate Factorial using standard values with outputs
Standard values – consider the following code is universally applicable- with sample outputs.
class Factoral
{
public static void main(String arg[])
{
int n=5,fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factoral="+fact);
}
}
Output:
Example 2:
Java Program Using For Loop
Among all three loops, for loop is probably the most used loop. For loop are two types mainly:
- for each style of for loop
- normal for loop
class Factorial
{
public static void main(String arg[])
{
long n,fact=1;
Scanner sc=new Scanner(System.in);
System.out.println("enter number");
n=sc.nextLong();
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("fact="+fact);
}
}
Output:
7 = 5040
Example 3:
Using Command Line Arguments
import java.util.Scanner;
class Factorl
{
public static void main(String args[])
{
long n,fact=1;
n=Long.parseLong(args[0]);
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("fact="+fact);
}
}
Output:
fact = 362880
Example 4:
Using Function
import java.util.Scanner;
class Factorl
{
public static void main(String args[])
{
long n,fact=0;
n=Long.parseLong(args[0]);
fact=factCal(n);
System.out.println("fact="+fact);
}
static long factCal(long x)
{
long fact=1;
for(int i=1;i<=x;i++)
{
fact=fact*i;
}
return fact;
}
}
Output:
fact = 3628800
Example 5:
Using Recursion
Recursion: A Recursion is a function call itself – you can check out more information about what is recursion in java here?
class Factorl
{
public static void main(String arg[])
{
long n;
Scanner sc=new Scanner(System.in);
System.out.println("enter number");
n=sc.nextLong();
long f=Factorl.fact(n);
System.out.println("factorial="+f);
}
static long fact(long n)
{
if(n<=0)
return 1;
return Factorl.fact(n-1)*n;
}
}
Output:
30
Factorl=8764578968847253504
Example 6:
Using while loop
import java.util.Scanner;
class Factrl
{
public static void main(String arg[])
{
long n,fact=1;
Scanner sc=new Scanner(System.in);
System.out.println("enter number");
n=sc.nextLong();
int i=1;
while(i<=n)
{
fact=fact*i;
i++;
}
System.out.println("fact="+fact);
}
}
Output:
10
fact=3628800
how to find factorial in java – how to find factorial in java – how to find factorial in java – how to find factorial in java – how to find factorial in java