0019-Factorial
問題(外部リンク)
実装の概要
が成り立つので再帰を用いて解きます。スタックオーバーフローについてはnが20以下となっているため特に気にする必要はありません。
終了条件についてはきちんと定義しておく必要があります。が終了条件です。なお、今回の入力ではありえませんが、です。
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); } } }