본문 바로가기

Algorithms/30 Days of Code

Day 9: Recursion

Recursive Method for Calculating Factorial 

Task 
Write a factorial function that takes a positive integer,  as a parameter and prints the result of  ( factorial).

Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of .

Input Format

A single integer,  (the argument to pass to factorial).

Constraints

  • Your submission must contain a recursive function named factorial.

Output Format

Print a single integer denoting .

Sample Input

3

Sample Output

6

Explanation

Consider the following steps:

From steps  and , we can say ; then when we apply the value from  to step , we get . Thus, we print  as our answer.


풀이

import java.io.*;

import java.util.*;

import java.text.*;

import java.math.*;

import java.util.regex.*;


public class Solution {


    static int factorial(int n) {

        // Complete this function

        if (n == 1){

            return n;

        }

        return n * factorial(n - 1);

    }


    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int n = in.nextInt();

        int result = factorial(n);

        System.out.println(result);

    }

}



'Algorithms > 30 Days of Code' 카테고리의 다른 글

Day 11: 2D Arrays  (0) 2018.02.20
Day 10: Binary Numbers  (0) 2018.02.19
Day 8: Dictionaries and Maps  (0) 2018.02.19
Day 7: Arrays  (0) 2018.02.19
Day 6: Let's Review  (0) 2018.02.14