# Thread: factorial numbers in java script

1. Registered User
Join Date
Dec 2005
Posts
1

## factorial numbers in java script

hey guys, i have a problem while writing factorial calculations in java script.. the calculation im looking to answer is :

z = x! / (x-y)!

the following is my code so far:

<html>

function factorial(n) {
if ((n == 0) || (n == 1))
return 1
else {
var result = (n * factorial(n-1) );
return result
}
}

<script language = "javascript">

<!--

var x = 0;
var y = 0;
var z = 0;

x = window.prompt("Enter first number..");
x = parseInt(x);

y = window.prompt("Enter second number..");
y = parseInt(y);

z = (factorial x / factorial (x-y));

alert("THE ANSWER IS " + z);

//-->

</script>

<body>

</body>

any comments would be great..

2. 1. Posting using the code tags makes us readers more willing to help
2. I would put the function factorial in the script.
3. What error are you getting?

3. I havent gone through all of your code but this is one detail that I noticed:

HTML Code:
`z = (factorial(x) / factorial (x-y));`
instead of
z = (factorial x / factorial (x-y));

4. Registered User
Join Date
Oct 2008
Posts
3
hi Patrick,

u have not right the following like this:
var x = 0;
var y = 0;
var z = 0;

u have to put comma (,) after each statement exept the last one (

so it must look like this:

var x = 0,
var y = 0,
var z = 0;

and in the propmt it should look like:

window.prompt("Enter first number", "0");

that what i notice so far

i hope that i help u cuz am not sure 100&#37;

good luck

5. Registered User
Join Date
Oct 2008
Posts
3
hi Patrick,

u have not right the following like this:
var x = 0;
var y = 0;
var z = 0;

u have to put comma (,) after each statement exept the last one (

so it must look like this:

var x = 0, y = 0, z = 0;

and in the propmt it should look like:

window.prompt("Enter first number", "0");

that what i notice so far

i hope that i help u cuz am not sure 100%

good luck

6. Registered User
Join Date
Feb 2008
Posts
1,666
I used this function:
Code:
```Math.factorial = function(n)
{
if(typeof n == 'string') n = Number(n);
if(typeof n != 'number' || isNaN(n))
{
alert("Factorial requires a numeric argument.");
return null;
}
if (n < 2) return 1;
return (n * Math.factorial(n-1));
}```
and this to test it:
HTML Code:
```<form action="">
<p><input type="text" name="T1" size="6">
<input type="button" value="Factorial"
onclick="T2.value = Math.factorial(T1.value); return true;">
= <input type="text" name="T2" size="12" readonly></p>
</form>```
Otherwise, as pointed out, the syntax here is incorrect:
Code:
`z = (factorial x / factorial (x-y));`
Last edited by MrNobody; 11-18-2008 at 03:32 PM.

#### Thread Information

##### Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•