Java算法01-实现阶乘的几种基本方法

1. 阶乘公式

n!=1×2×3×...×n

阶乘也可以用递归方式定义:

0!=1,n!=(n-1)!×n

2. 使用循环实现阶乘

n!=1×2×3×...×n

/**
 * 1、使用循环实现阶乘
 */
public class Factorial {
    public static int fact(int num) {
        int n = 1;
        // 查验输入错误
        if (num < 0) {
            System.out.println("输入错误,必须为正整数");
            return -1;
        } else {
            // 循环num次
            for (int i = 1; i <= num; i++) {
                // 每次循环一次就进行一次乘法运算
                n = n * i;
            }
            // 返回阶乘结果n
            return n;
        }
    }
    public static void main (String[] args) {
    // 这里的fact方法在类Factorial中属于静态方法,不应该用类实例来访问静态成员,用类Factorial直接访问静态成员
    int count = fact(3); 
    System.out.println(count);
  }
}

3. 使用递归实现阶乘

0!=1,n!=(n-1)!×n

public class Factorial {
    public static int fact(int n) {
        // 验错
        if (n < 0) {
            System.out.print("输入错误,必须为正整数");
            return -1;
        } else if (n == 1) {
            return 1;
        }
        // n的阶乘就等于n乘(n-1)的阶乘
        return fact(n - 1) * n;
    }
    public static void main(String[] args) {
        System.out.println(fact(3));
    }
}

 

posted @ 2021-04-27 18:00  TSCCG  阅读(3201)  评论(0编辑  收藏  举报