Jump to content


Problem with Javascript


2 replies to this topic

#1 windtalker

    Young Padawan

  • Members
  • Pip
  • 12 posts

Posted 22 December 2007 - 07:59 AM

Hi,
I am newby about Javascript, and I am trying to create my own faculty calculator (math).
for example if you want to calculate 5 - faculty = 1*2*3*4*5 = 120

Now, I've managed to do this, but here's my problem:
My script works when I fill in an number, for example 5. When I calculated this, I want to calculate the 6 faculty, tats works too. But when I fill a number smaller than the first number (in this case 5), it doesn't work.

Here's my java script:
<html>
<head>
</head>
<body>
<script language="javascript">
	
	var a = 1;
	var n = 1;
	
	function Calculate(x){
	
		while (n<=x) {
			a = a * n;
			n++;
		
			document.CalcFaculty.Output.value = a
		}
	}
</script>

<form name = "CalcFaculty">
<input type="text" name="Input" size="30"><br>
<input type="button" value="Calculate n-faculty" onClick="Calculate(document.CalcFaculty.Input.value)">
<input type="reset" value="Reset"><br>
<input type="text" name="Output" size="30">
</form>
</body>
</html>

Someone can help me?

Thx in advance

#2 rc69

    PHP Master PD

  • P2L Staff
  • PipPipPipPip
  • 3,827 posts
  • Gender:Male
  • Location:Here
  • Interests:Web Development

Posted 23 December 2007 - 01:09 AM

You mean factorial right? Faculty is a staff member of a school, so why you would want to calculate one of them is beyond me.

function Calculate(n){
	var result = 1; // reason: 1*x == x;
	for(var x=n; x > 0; x--){
		result *= x;
	}

	document.CalcFaculty.Output.value = result;
}
This is also commonly defined recursively.
function Calculate(n){
	if(n <= 1){
		return 1;
	}

	return n * Calculate(n-1);
}
Note though, that while the recursive implementation may be easier to understand, the loop is more efficient.

Edited by rc69, 23 December 2007 - 01:14 AM.


#3 windtalker

    Young Padawan

  • Members
  • Pip
  • 12 posts

Posted 23 December 2007 - 06:06 AM

View Postrc69, on Dec 23 2007, 07:09 AM, said:

You mean factorial right? Faculty is a staff member of a school, so why you would want to calculate one of them is beyond me.

function Calculate(n){
	var result = 1; // reason: 1*x == x;
	for(var x=n; x > 0; x--){
		result *= x;
	}

	document.CalcFaculty.Output.value = result;
}
This is also commonly defined recursively.
function Calculate(n){
	if(n <= 1){
		return 1;
	}

	return n * Calculate(n-1);
}
Note though, that while the recursive implementation may be easier to understand, the loop is more efficient.

Thx man,
and sorry, but my English isn't great :P





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users