Header Ad

HackerRank Day 9 Recursion 3 30 days of code solution

In this HackerRank Day 9 Recursion 3 30 days of code problem set, we need to develop a program that takes an integer input and then prints the factorial of that integer input on the output screen. 

Day 9 Recursion 3 | 30 days of code solution | Hackerrank


Problem solution in Python 2 programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
def factorial(n):
    if n==0 or n==1:
        return 1
    else:
        return factorial(n-1)*n
print factorial(int(raw_input()))


Problem solution in Python 3 programming.

#!/bin/python3

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()


Problem solution in java programming.

import java.io.*;
import java.util.*;

public class Solution {

    public static int factorial(int n){
        return (n > 1) ? n * factorial(n-1) : 1;
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        scan.close();
        System.out.println(factorial(n));
    }
}


Problem solution in c++ programming.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

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

int main() {
    int n;
    cin >> n;
    int r = factorial(n);
    cout << r << endl;
    return 0;
}


Problem solution in c programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int factorial(int);
int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int n;
    scanf("%d",&n);
    printf("%d",factorial(n));
    return 0;
}

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


Problem solution in Javascript programming.

function processData(input) {
    //Enter your code here
    var N = parseInt(input),
        num = 1;
    
    function factorial(N){
        if (N > 1){
            num = num * N;
            factorial(N-1);
        }
    }
    factorial(N);
    console.log(num);
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Post a Comment

0 Comments