[Hackerrank] Recursion 3

dhjo ㅣ 2021. 10. 10. 14:55

Objective
Today, we are learning about an algorithmic concept called recursion. Check out the Tutorial tab for learning materials and an instructional video.

Recursive Method for Calculating Factorial

Function Description
Complete the factorial function in the editor below. Be sure to use recursion.

factorial has the following paramter:

  • int n: an integer

Returns

  • int: the factorial of n

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

Input Format

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

Constraints

  • 2 <= n <= 12
  • Your submission must contain a recursive function named factorial.

Sample Input

3

Sample Output

6

Explanation

Consider the following steps. After the recursive calls from step 1 to 3, results are accumulated from step 3 to 1.

 


 

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'factorial' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts INTEGER n as parameter.
     */

    public static int factorial(int n) {
    // Write your code here
        int answer = 0;
        for(int i=0; i<=n; i++) {
            answer *= i;
        }
        return answer;
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        int result = Result.factorial(n);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

'알고리즘 > Hackerrank' 카테고리의 다른 글

[Hackerrank] 2D Arrays  (0) 2021.10.10
[Hackerrank] Binary Numbers  (0) 2021.10.10
[Hackerrank] Dictionaries and Maps  (0) 2021.10.05
[Hackerrank] Arrays  (0) 2021.10.02
[Hackerrank] Let's Review  (0) 2021.10.02