# HackerRank Day 9: Recursion 3 – 30 Days of Code Solution

In this article, we will be solving HackerRank Day 9: Recursion 3 problem, part of 30 Days of Code. Majorly, we will use Python3 and Java15 to solve the problem.

#### Objective:

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

#### Function Description

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

Factorial has the following parameter:

• int n: an integer

#### Returns

• int: the factorial of n

Note: If you 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 steps 1 to 3, results are accumulated from steps 3 to 1.

1. factorial(3) = 3 * factorial(2) = 3 * 2 = 6
2. factorial(2) = 3 * factorial(1) = 2 * 1 = 2
3. factorial(1) = 1

You can find all the source code on my GitHub profile: https://github.com/uttammanani/HackerRank-30-Days-of-Code

### Solution Day 9: Recursion 3 in Python3

``````#!/bin/python3

import math
import os
import random
import re
import sys

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

def factorial(n):
if n == 1:
return 1
else:
n = n * factorial(n-1)
return n

if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

n = int(input().strip())

result = factorial(n)

fptr.write(str(result) + '\n')

fptr.close()
``````

### Solution Day 9: Recursion 3 in Java15

``````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) {
return (n > 1) ? n * factorial(n-1) : 1;
}

}

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

int result = Result.factorial(n);

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

bufferedWriter.close();
}
}
``````