- class Demo
- {
- public static void main(String[] args)
- {
- int product = factorial_1(6);
- System.out.println(product);
- }
- public static int factorial_1(int a) //第一种方法,迭代
- {
- int product = 1;
- for(int i = 1;i<=a;i++)
- {
- //System.out.println("i = "+i+" product = "+product);
- product *= i;
- }
- return product;
- }
- public static int factorial_2(int a)//第二种方法递归
- {
- if(a <= 1)
- {
- return 1;
- }
- return a * factorial_2(a-1);
- }
- }
复制代码 |