Finding Factorial of a Number in Java

This illustrates finding factorial of a number algorithm in Java. Here i didn't use any methods for finding factorial, it is just the logic.

import java.util.*;
class FindFactorial
    public static void main(String args[])
    int n;
    System.out.println("Enter the number");
    Scanner s=new Scanner(;

    // If user enters 0 then 0!=1
    long f=1;

        for(int i=n;i>=1;i--)
    System.out.println("Factorial of "+n+" is "+f);

Sample Output

Enter the number
Factorial of 7 is 5040


f=1: When user gives 0 as input, then 0!=1
The Loop: Loop is looped till n decreases to 1
f*=i: It is equal to f=f*i;. This is a simple factorial logic.

For people, who don't know what is factorial of a number, i could explain them with the help of examples for a better understand.

Also see Finding Divisors of a number in Java

In this way, we can simply find factorial of a number without using any factorial function not only in Java but in any language.

Posted by at on

Tags: Playing with Numbers,