Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 2

import java.util.

*;

class Factorial {
        public static void main(String args[]) {
                Scanner sc = new Scanner(System.in);
                int n = sc.nextInt();
                int result = factorial(n);

                System.out.println(result);
    }

        static int factorial(int n) {


                // System.out.println("Printing n: " + n);
                // Base case
                // if n == 1, then we have to return.
                if (n < 0) {
                        // System.out.println("This shouldn't happen");
                        return -1;
        }
                if (n == 1 || n == 0) {
                        // System.out.println("Hit the base case where n = " + n);
                        return 1;
        }
        
                // Recursion
                int factorialOutput = n * factorial(n-1);
                return factorialOutput;
    }
}

// Milestone 1: Understand the problem clearly


// - Ask questions & clarify the problem statement clearly.
// - Take an example or two to confirm your understanding of the input/output & extend it to
testcases
// 0! = 1
// 1! = 1
// 2! = 2*1 = 2
// 3! = 3*2*1 = 6
// 20! = ?
// // Milestone 2: Finalize approach & execution plan
// // - Understand what type of problem you are solving.
// Math, Logic fairly straightword
// // - Brainstorm multiple ways to solve the problem and pick one
// 1. n!: i = 1 to n; multiple all the number
// 2. Recursion [Chosen]
//          n! = n * (n-1)!
//          5! = 5 * (4*3*2*1)
//                = 5 * 4!
//          Termination Condition:
//          n = 1 -> you can terminate.

// // - Get to a point where you can explain your approach to a 10 year old
// // - Take a stab at the high level logic & write it down.
// long factorial(int n) {
//          // Base case
//          // if n == 1, then we have to return.
    
//          // Recursion
//          long factorialOutput = n * factorial(n-1);
//          return factorialOutput;
// }
// - Try to offload processing to functions & keeping your main code small.

// Milestone 3: Code by expanding your pseudocode


// - Make sure you name the variables, functions clearly.
// - Avoid constants in your code unless necessary; go for generic functions, you can use
examples for your thinking though.
// - Use libraries as much as possible

// Milestone 4: Prove to the interviewer that your code works with unit tests
// - Make sure you check boundary conditions

// Time & storage complexity


// Suggest optimizations +

You might also like