factorialiterative.js
/**
* Factorial: Iterative
Description
Write a program that computes the factorial of a given integer.
Your implementation should be iterative in nature. Factorial of an
integer n is defined as Factorial(n) = 1*2*3*....*(n-2)*(n-1)*n.
Factorial(0) is defined as 1. Factorial of a negative integer is undefined.
Input format
One line containing an integer n.
Output format
One line containing the factorial of n.
Sample input
5
Sample output
120
Explanation
Factorial of 5 is 1*2*3*4*5 which is 120.
Sample input
-4
Sample output
undefined
Explanation
Factorial of a negative integer is undefined.
*/
let fs = require("fs");
let data = fs.readFileSync(0, 'utf-8');
let idx = 0;
data = data.split('\n');
function readLine() {
idx++;
return data[idx - 1];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
function factorial_iterative(number) {
if (number > 0)
{
let ans = 1
for (let i = 1; i <= number; i++) { //i=1, i=2, i=3, i=4, i=5 (i=6<= 5
false exit the loop)
ans = ans * i// 1*1=1, 1*2=2, 2*3=6, 6*4=24, 24*5=120
}
return ans
}
else if (number == 0) {
return 1
}
else if (number < 0) {
return 'undefined'
}
}
let number = parseInt(readLine()); // 5
console.log(factorial_iterative(number)); // calling or invoking the function
//////////////////////////////////////////////////////////////////////////////////////////////
TERMINAL:

Comments
Post a Comment