Skip to content

Instantly share code, notes, and snippets.

@pleabargain
Last active February 19, 2017 14:27
Show Gist options
  • Save pleabargain/0d90cdcb4578d5de05ef3a1e454e1421 to your computer and use it in GitHub Desktop.
Save pleabargain/0d90cdcb4578d5de05ef3a1e454e1421 to your computer and use it in GitHub Desktop.
factor a number in js with simple error catching
function factorial(num)
{
// If the number is less than 0, reject it.
if (num < 0) {
//error message to user
console.log('use a number above 1');
return -1;
}
// If the number is 0, its factorial is 1.
else if (num == 0) {
return 1;
}
let tmp = num;
//as long as the num is more than 2
while (num-- > 2) {
//multiply the num
tmp *= num;
}
return tmp;
}
let result = factorial(18);
console.log(result);
// Output: 6402373705728000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment