Day 9: Recursion - HackerRank 30 days of code solution

Objective
Today, we're learning and practicing an algorithmic concept called Recursion.
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.

Solution :


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);
        
            while(in.hasNext())
            {
           long n = in.nextLong();
        long factofnum =factorial(n);
        System.out.println(factofnum);
        }    
    }
    
    public static long factorial(long n)
        {
        if(n==0 || n==1)
            {
            return 1;
        }
        else
            return n*factorial(n-1);
    }
}

Comments

Popular posts from this blog

Day 4: Class vs. Instance - HackerRank 30 days of code solution

Day 27: Testing - HackerRank 30 days of code solution

Day 11: 2D Arrays - HackerRank 30 days of code solution