Javascript: Build a Factorial function using loop and recursion.
Yong Liang
Posted on March 11, 2019
Overview
Factorial of n means n*(n-1)*(n-2)*(n-3)..., so factorial of 5 would be 5*4*3*2*1 which equal to 120. In this article, we will implement factorial using a simple for loop and a simple recursion, using javascript.
For loop solution
This is a simple loop that iterates as many times as the number n, and times the incrementing i to find the result.
Recursion solotion
A recursive function should have two basic components - 1. base case; 2. recursive case. When the base case condition is met, the function will stop, otherwise, the function will keep calling itself, similar to how loops iterate.
n is printed in order here because each time the function calls itself, it subtract by 1 until n reaches 1. Notice that each time this function calls itself, the n value updates.
Knight Tour using backtracking
https://www.geeksforgeeks.org/the-knights-tour-problem-backtracking-1/
Posted on March 11, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024