Skip to content

Commit 759e81d

Browse files
committed
Create factorial.js
This program calculates and displays the factorial for a user-input number.
1 parent 61ea916 commit 759e81d

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

maths/factorial.js

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
author: PatOnTheBack
3+
license: GPL-3.0 or later
4+
5+
Modified from:
6+
https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_python.py
7+
8+
This script will find the factorial of a number provided by the user.
9+
10+
More about factorials:
11+
https://en.wikipedia.org/wiki/factorial
12+
*/
13+
14+
function calc_range(num) {
15+
// Generate a range of numbers from 1 to `num`.
16+
"use strict";
17+
var i = 1;
18+
var range = [];
19+
while (i <= num) {
20+
range.push(i);
21+
i += 1;
22+
}
23+
return range;
24+
}
25+
26+
function calc_factorial(num) {
27+
"use strict";
28+
var factorial;
29+
var range = calc_range(num);
30+
31+
// Check if the number is negative, positive, null, undefined, or zero
32+
if (num < 0) {
33+
return "Sorry, factorial does not exist for negative numbers.";
34+
}
35+
if (num === null || num === undefined) {
36+
return "Sorry, factorial does not exist for null or undefined numbers.";
37+
}
38+
if (num === 0) {
39+
return "The factorial of 0 is 1.";
40+
}
41+
if (num > 0) {
42+
factorial = 1;
43+
range.forEach(function (i) {
44+
factorial = factorial * i;
45+
});
46+
return "The factorial of " + num + " is " + factorial;
47+
}
48+
}
49+
50+
// Run `factorial` Function to find average of a list of numbers.
51+
var num = prompt("Enter a number: ");
52+
alert(calc_factorial(num));

0 commit comments

Comments
 (0)