# Algorithms: factorial

My solution attempts to bulletproof the function. I hope I have succeeded.

/* Function: Factorial of a non-negative integer number.
** @summary
** @param {number}
** @return {number} Factorial is returned, or 0 if invalid Number
*/
function factorial(num) {
var fNum = false;
var fName = "factorial ";

if ( typeof num !== “number” ) {
console.log(fName + num + " invalid type - must be number")
} else if ( num < 0 ) {
console.log(fName + num + " must be a positive integer")
} else {
if ( num === 0 ) { num = 1; } // 0! = 1 is special case.
fNum = num;
while ( --num > 0 ) {
fNum *= num;
if ( !Number.isSafeInteger(fNum) ) {
console.log (fName + “result > Safe Integer range”);
fNum = false;
break;
}
}
}
return fNum;
}

Is there a way to cut and paste so that my code indentation isn’t obliterated?

@KerryRuddock

This is very useful cheatsheet for markdown…you use triple back-ticks and call javascript for specific syntax highlighting.

here you go

``````
/* Function: Factorial of a non-negative integer number.
** @summary
** @param {number}
** @return {number} Factorial is returned, or 0 if invalid Number
*/
function factorial(num) {
var fNum = false;
var fName = "factorial ";

if ( typeof num !== "number" ) {
console.log(fName + num + " invalid type - must be number")
} else if ( num &lt; 0 ) {
console.log(fName + num + " must be a positive integer")
} else {
if ( num === 0 ) { num = 1; } // 0! = 1 is special case.
fNum = num;
while ( --num &gt; 0 ) {
fNum *= num;
if ( !Number.isSafeInteger(fNum) ) {
console.log (fName + "result &gt; Safe Integer range");
fNum = false;
break;
}
}
}
return fNum;
}
[/quote]

``````

Thanks for the link. I will see if I can find a practice site for markdown editing before my next post.

@KerryRuddock

You should have “preview” link when you put in your text here on this forum?

## See this?

`Code here`

Also you will eventually make one of your very own markdown previewer! Like this one

``````function doSomething () {
console.log('show this line on the console');
}
``````

ah… got it… thanks.

1 Like