Write a Java Program to find Factorial of a Given Number

Write a Java Program to find Factorial of a Given Number thumbnail
7K
By Dhiraj Ray 02 January, 2018

Description

Write a program to find factorial of a given number is a common java program asked in any interview to freshers.The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example factorial of 4 is 4*3*2 = 24.There are 2 ways to find a factorial of a given number - One by using for loop and the other using recursion.Following java program uses for loop to find factorial of a given number.

Factorial.java
package com.devglan;

public class Factorial {

    public long findFactorial(int num){
		if(num < 1){
				System.out.println("Please provide non-negative number.");
        }
        long factorial = 1;
        for (long i = num; i > 1; i--) {
            factorial = factorial * i;
        }
        return factorial;
    }

    public static void main(String [] args){
        Factorial factorial = new Factorial();
        int num = 34;
        System.out.println("Factorial of " + num + " is : " + factorial.findFactorial(num));
    }
}

Explanation

Use for loop starting from the number itself and multiply with a decrement number and keeps on accumulating the result in the same variable untill 1 is reached.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.