Problem
Objective
Today, we're learning and practicing an algorithmic concept called Recursion. Check out the Tutorial tab for learning materials and an instructional video!
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.
How I solved the problem
# 팩토리얼 문제는 대표적인 재귀함수 호출 ! (recursion : 재귀)
# 스택의 원리를 잘 이해해야함.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { // Complete the factorial function below. static int factorial(int n) { if (n == 1) { return n; } else { return factorial(n - 1) * n; //factorial 함수를 계속 호출함 } } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int result = factorial(n); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); bufferedWriter.close(); scanner.close(); } } | cs |
[출처 : https://www.hackerrank.com ]
'1 Day 1 Algorithms' 카테고리의 다른 글
[2018.12.26] Inheritance (0) | 2018.12.26 |
---|---|
[2018.12.21] Binary Numbers (0) | 2018.12.21 |
[2018.12.19] Mini-Max Sum (0) | 2018.12.19 |
[2018.12.19] Dictionaries and Maps (0) | 2018.12.19 |
[2018.12.18] Staircase (0) | 2018.12.18 |
댓글