I♥TLE

Java、オンラインジャッジなど

0019-Factorial

問題(外部リンク)

Factorial | Aizu Online Judge

実装の概要

n!=n\cdot (n-1)!が成り立つので再帰を用いて解きます。スタックオーバーフローについてはnが20以下となっているため特に気にする必要はありません。
終了条件についてはきちんと定義しておく必要があります。1!=1が終了条件です。なお、今回の入力ではありえませんが、0! = 1です。

public class Main {
 
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
         
        System.out.println(Calc.fact(n));
    }
 
}
 
class Calc {
    public static long fact (int n){
        if(n == 0|| n==1){
            return 1;
        }
        else {
            return n*fact(n-1);
        }
    }
}