DEV Community

Yong Liang
Yong Liang

Posted on • Updated on

Javascript: Build a Factorial function using loop and recursion.

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/

Top comments (0)