Factorial

How to calculate factorial

Page 1 of 1

1 Replies - 23650 Views - Last Post: 01 December 2007 - 02:14 PM

#1 bostonrob  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 15-November 07

Factorial

Post icon  Posted 30 November 2007 - 06:39 PM

Hello
I have run into a stack overflow with this code.
This program should work with any number.
I think I might need an array?
Any suggestions would be appreciated.

Rob

<html>
<head>
<title>Javascipt Lessons</title>


<script language="Javascript">

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

answer = document.MyForm.answer.value
}

}


</script>
</head>

<body>
<CENTER>
Calculate Factorial of a Number Program
</body>
<form name="MyForm">
<CENTER>
<BR>
<BR>
<BR>
<BR>
<P>Enter a positive integer <INPUT TYPE=text NAME=n VALUE="" SIZE=5>
and then press <input type="button" value="THIS BUTTON" onclick="factorial()"> for answer!
<P>Your Answer is <INPUT TYPE=text NAME=answer VALUE="" SIZE=5>
</FORM>



</body>
</html>

Is This A Good Question/Topic? 0
  • +

Replies To: Factorial

#2 ahmad_511  Icon User is offline

  • MSX
  • member icon

Reputation: 131
  • View blog
  • Posts: 722
  • Joined: 28-April 07

Re: Factorial

Posted 01 December 2007 - 02:14 PM

Hi.
First of all, you have some unclosed Tags such as Center and Paragraph.
Also, on Calculation button, you called the function without passing it (n) parameter.
Now, at the function part
You tried to change the (answer) Text box value after the function returns the (result), which does not make since because the function is already terminated.
So depending on that do this
On button click
<input type="button" value="THIS BUTTON" onclick="MyForm.answer.value=factorial(MyForm.n.value)">



At the function
Remove the following line
answer = document.MyForm.answer.value 


That's will make it works fine

Regards
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1