Algorithm


Problem Name: 30 days of code - Day 9: Recursion 3

Problem Link: https://www.hackerrank.com/challenges/30-recursion/problem?isFullScreen=true

In this HackerRank in 30 Days of Code - Day 9: Recursion 3 problem solution,

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
 
Recursive Method for Calculating Factorial
 
Function Description


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

a factorial has the following parameter:

  • int n: an integer


Returns

  • int: the factorial of


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

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

 

 

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();

// the factorial function .
int factorial(int n) {
if(n<=0)
    return 1;
else
    return n*factorial(n-1);

}

int main()
{
    FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");

    char* n_endptr;
    char* n_str = readline();
    int n = strtol(n_str, &n_endptr, 10);

    if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }

    int result = factorial(n);

    fprintf(fptr, "%d\n", result);

    fclose(fptr);

    return 0;
}

char* readline() {
    size_t alloc_length = 1024;
    size_t data_length = 0;
    char* data = malloc(alloc_length);

    while (true) {
        char* cursor = data + data_length;
        char* line = fgets(cursor, alloc_length - data_length, stdin);

        if (!line) { break; }

        data_length += strlen(cursor);

        if (data_length  <  alloc_length - 1 || data[data_length - 1] == '\n') { break; }

        size_t new_length = alloc_length << 1;
        data = realloc(data, new_length);

        if (!data) { break; }

        alloc_length = new_length;
    }

    if (data[data_length - 1] == '\n') {
        data[data_length - 1] = '\0';
    }

    data = realloc(data, data_length>;

    return data;
}
Copy The Code & Try With Live Editor

#2 Code Example with C++ Programming

Code - C++ Programming


#include <iostream>

using namespace std;

int factorial(int n) {
    if (n == 1) return 1;
    return factorial(n - 1) * n;
}

int main() {
    int N;
    cin >> N;

    cout << factorial(N);

    return 0;
}
Copy The Code & Try With Live Editor

#3 Code Example with C# Programming

Code - C# Programming


using System;
using System.Collections.Generic;

class Solution
{
    static void Main(String[] args)
    {
        var n = int.Parse(Console.ReadLine());

        Console.WriteLine(factorial(n));
    }

    static int factorial(int n)
    {
        if (n == 1) return 1;

        return factorial(n - 1) * n;
    }
}
Copy The Code & Try With Live Editor

#4 Code Example with Golang Programming

Code - Golang Programming


package main

import "fmt"

func factorial(n int) int {
	if n == 1 || n == 0 {
		return 1
	}
	return n * factorial(n-1)
}

func main() {
	var n int
	fmt.Scan(&n)

	fmt.Println(factorial(n))
}
Copy The Code & Try With Live Editor

#5 Code Example with Java Programming

Code - Java Programming


import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        in.close();
        System.out.println(factorial(n));
    }

    private static int factorial(int n) {
        if (n == 1) return 1;
        return factorial(n - 1) * n;
    }
}
Copy The Code & Try With Live Editor

#6 Code Example with Javascript Programming

Code - Javascript Programming


function factorial(n) {
    if(n<0) {
        return 1;
    }else if(n==1){
        return 1;
    }else{
        return n * factorial(n-1>;
    }
}
Copy The Code & Try With Live Editor

#7 Code Example with Python Programming

Code - Python Programming


import math
import os
import random
import re
import sys

# Complete the factorial function below.
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())

    result = factorial(n)

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

    fptr.close()
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Day 8: Dictionaries and Maps solution in Hackerrank - Hacerrank solution C, C++, C#, java, Js, PHP, Python in 30 days of code
Next
[Solved] Day 10: Binary Numbers solution in Hackerrank - Hacerrank solution C, C++, C#, java, Js, PHP, Python & GO in 30 days of code