Type Here to Get Search Results !

Day 9: HackerRank 30 Days Of Code Solution By CodingHumans | Recursion 3 |

0


Day 9: Recursion 3

What is Recursion ?

Recursion is a process in which function calls itself. Recursion involves splitting a problem into two parts: a base case and a recursive case. The problem is divided into smaller sub problems which are then solved recursively until such time as they are small enough and meet some base case; once the base case is met, the solutions for each sub problem are combined and their result is the answer to the entire problem.If the base case is not met, the function's recursive case calls the function again with modified values. The code must be structured in such a way that the base case is reachable after some number of iterations, which means  that each subsequent modified value should bring you nearer to the base case ,otherwise, we will be stuck in an infinite loop .

Aim 

To know the  algorithmic concept called Recursion. What actually is Recursion  is and how it works.
How to calculate Factorial using recursion 
    fatorial(N) = N x factorial(N-1)

Mission 

Coders you need to write a factorial function that takes a positive integer,N  as a parameter and prints the result of  (N factorial).
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 Style

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

Constraints

2<=N<=12

Your submission must contain a recursive function named factorial.

Output Style

Print a single integer denoting N! .

Sample Input

4

Sample Output

24 

Explanation

Consider the following steps:

factorial(4) = 4 x factorial (3)
factorial(3) = 3 x factorial (2)
factorial(2) = 2 x factorial (1)
factorial(1) =1
  
4 x 3 x 2 x 1 =24 is the answer.



Recommended: Please try your approach on your integrated development environment (IDE) first, before moving on to the solution.

Few words from CodingHumans : Don't Just copy paste the solution, try to analyze the problem and solve it without looking by taking the the solution as a hint or a reference . Your understanding of the solution matters.

HAPPY CODING 😁





Solution:
( java )


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 {
public static final Scanner sc= new Scanner(System.in);
    // Complete the factorial function below.
    static int factorial(int n) {
        if(n<=1){
            return 1;
        }
        else{
            return n * factorial(n-1);
        }
    }
    public static void main(String agrs[]){
        int a=sc.nextInt();
        System.out.println(factorial(a));
    }
}



If you have any doubts regarding this problem or  need the solution in other programming languages then leave a comment down below . 

Post a Comment

0 Comments

Top Post Ad

Below Post Ad