Factorial

使用循环计算阶乘

import java.util.Scanner;
public class Factorial {
    private static Scanner input;
    static long fact(int n)
    {
        int i;
        long result=1;
        
        for(i=1;i<=n;i++)
        {
            result*=i;
        }
        return result;
    }
    public static void main(String[] args)
    {
        int i;
        System.out.println("enter a number");
        input = new Scanner(System.in);
        i=input.nextInt();
        System.out.println("the factorial of "+i+" is "+fact(i));
    }
}

使用递归计算阶乘

static long fact(int n)
    {
        if(n<=1)
            return 1;
        else
            return n*fact(n-1);
    }

你可能感兴趣的:(Factorial)