diff --git a/Factorial_6/factorial.js b/Factorial_6/factorial.js new file mode 100644 index 0000000..d12ab68 --- /dev/null +++ b/Factorial_6/factorial.js @@ -0,0 +1,33 @@ + +//1. Using For Loop. + +function factorial(n){ + let answer = 1; + if (n == 0 || n == 1){ + return answer; + }else{ + for(var i = n; i >= 1; i--){ + answer = answer * i; + } + return answer; + } + } + let n = 4; + answer = factorial(n) + console.log("The factorial of " + n + " is " + answer); + + +//2. Using Recursion. + +function factorial(n){ + //base case + if(n == 0 || n == 1){ + return 1; + //recursive case + }else{ + return n * factorial(n-1); + } +} +let n = 4; +answer = factorial(n) +console.log("The factorial of " + n + " is " + answer); \ No newline at end of file diff --git a/README.md b/README.md index 13d142d..f1c669f 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ __Algorithms practiced using JS__ 3. Finding the Most Recurring Character 4. Sentence Capitalization 5. Palindromes +6. Factorial of a number ## Explanation 1. String reversing @@ -447,15 +448,65 @@ method tests whether all elements pass the test or not which is implemented by p

-6. Name +6. Factorial of a number -__The challenge:__

+

The Factorial of a non-negative number ,n , is computed as the product of all integers between 1 and n (both inclusive).

+ * factorial(n) = n * (n-1) * ..... * 1
+ It can be thought of as:
+ * factorial(n) = n * factorial(n-1).


+__The challenge:__

Given a number, print the factorial of this number

-__Algorithmic Thinking:__

+```js + answer = factorial(n) // will return the factorial. +``` +__Algorithmic Thinking:__

Approaches
+There are two ways to compute the factorial of a number in JavaScript.

-__code Implementation:__

+1. Iterative
+2. Recursive

+Both of these approaches will be explored below.

+ + +__code Implementation:__

1. The Iterative approach

+Keeping in mind the first definition of a ​factorial, the variable i is initially set equal to n and is gradually decremented to 1. In each step, the result of the multiplication is stored in the variable answer.


+ +```js + function factorial(n){ + let answer = 1; + if (n == 0 || n == 1){ + return answer; + }else{ + for(var i = n; i >= 1; i--){ + answer = answer * i; + } + return answer; + } + } + let n = 4; + answer = factorial(n) + console.log("The factorial of " + n + " is " + answer); +``` +
+

2. The Recursive approach

+As stated above, the factorial of n can be found by finding the factorial of a number one less than n, and then multiplying this answer with n. So the factorial of n-1 can be thought of as a subproblem that needs to be computed first.


+ +```js + function factorial(n){ + //base case + if(n == 0 || n == 1){ + return 1; + //recursive case + }else{ + return n * factorial(n-1); + } + } + let n = 4; + answer = factorial(n) + console.log("The factorial of " + n + " is " + answer); +``` +