Defining methods Calculating factorials

Write a method that calculates the factorial of a given number.

The factorial of n is calculated by the product of integer number from 1 to n (inclusive). The factorial of 0 is equal to 1.

Sample Input 1:

0

Sample Output 1:

1

Sample Input 2:

5

Sample Output 2:

120
import java.util.Scanner;

public class Main {

    private static long factorial(long n) {
        long ans = 1L;

        if (n == 0L) {
            return ans;
        } else {
            for (long i = 1L; i <= n; i++) {
                ans = ans * i;
            }
            return ans;
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long n = Integer.parseInt(scanner.nextLine().trim());
        System.out.println(factorial(n));
    }
}
posted @ 2020-08-12 08:03  longlong6296  阅读(83)  评论(0)    收藏  举报