Return to Kroll Design home page

Flash Tutorials (with .FLA files included)

 
« Return

ActionScript 2

Compute the factorial of a number using a recursive function

Download the FLA file

The factorial of an integer is the product of the integers one through the number in question. For example, 4 factorial is 4 times 3 times 2 times 1 = 24. Both zero factorial and one factorial are 1. The factorial of negative numbers is undefined. This flash movie accepts input in a text box, and outputs the factorial of the number entered. First, it uses the 'parseInt' function to convert the entered text to an integer (if a number was typed in). It uses the 'isNaN' function to see if the number entered is not a number. The function calls itself, and is therefore what is known as a 'recursive' function.

// This recursive factorial function was created by David Kroll

function factorial (old_nbr) {
	if (isNaN(old_nbr)) {
		return "undefined" }
	else if (old_nbr == 0) {
		return 1 }
	else if (old_nbr < 0) {
	  return "undefined" }
	else if (old_nbr == 1) {
		return 1 }
	else if (old_nbr > 16) {
		return "something in the trillions or greater" }
	else {
		return (old_nbr * factorial(old_nbr - 1))	}
}

submit_btn.onRelease = function () {
    my_nbr = parseInt(input_txt.text);	
	output_nbr = factorial(my_nbr);	
}


 
« Return


©2012 Kroll Design    info@KrollDesign.net    781.910.3694
Last modified: 12/31/1969 7:00 PM