Reputation: 25
I have a question about an exercise (in JavaScript) regarding the factorial of an integer. I have two conditions that I can't resolve: The factorial of a negative number does not exist. How can I show this? Enter decimal numbers using decimal point: 1.54. I think the decimals can be factorial too. But how?
function fact(){
var i;
var number;
var f;
f = 1;
number = document.getElementById("number").value;
for(i = 1; i <= number; i++) {
f = f * i;
}
i = i - 1;
document.getElementById("result").innerHTML = "The factorial of the number " + i + " is: " + f ;
}
Enter a number: <input id = "number">
<button onclick = "fact()"> Factorial </button>
<p id = "result"></p>
Upvotes: 1
Views: 214
Reputation: 187134
The factorial of a negative number does not exist. How can I show this?
A simple if
statement should allow you to check the value of number
. If that value is below zero (meaning it's a negative number) then show a different message on the page:
if (number < 0) {
document.getElementById("result").innerHTML =
"Invalid input. A positive number is required";
}
Enter decimal numbers using decimal point:
1.54
. I think the decimals can be factorial too. But how?
Wikipedia defines factorial as follows:
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
Which means that a value of 1.54
is not valid, since it is not an integer.
What to do about that is up to you. Some ideas:
Math.round(number)
Math.floor(number)
if (Math.floor(number) === number)
Or as @0stone0 points out in a comment to this answer, fractional factorials can be a thing. I'm not sure how to convert that math to javascript. But the point is that it's up to you how you want to handle these edge cases.
Lastly, it's worth talking about this line:
number = document.getElementById("number").value;
Here number
is a string, not actually a number. This means it's the characters "123"
instead of the number 123
. You probably want to use parseInt
or parseFloat
on that value to make it a real number.
Javascript sometimes converts that string to a number for you when doing math operations, but it's not a good practice to rely on that as it can cause some bizarre and subtle bugs that are hard to understand.
Upvotes: 2