Factorials In Javascript (With Recursion)

24 Jun

To learn JavaScipt, I’m redoing some problems I’ve done to learn Ruby. Previously, I wrote a Ruby method to find a factorial of a number both recursively and non-recursively. You can read the original post here.

This is how you solve the same problem with Javascript:

Non-Recursively

//prompt user to enter a number to calculate the factorial
var num = prompt("What number do you want to find the factorial of?")

var factorial = function(n) {
	if(n == 0) {
		return 1
	} else {
		product = 1;
		for(i = 1; i <= n; i++) {
			product *= i;
		}
		return product;
	}
}

console.log(factorial(num));

Recursively

//prompt user to enter a number to calculate the factorial
var num = prompt("What number do you want to find the factorial of?")

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

console.log(factorial(num));
Advertisements

5 Responses to “Factorials In Javascript (With Recursion)”

  1. kjd (@RundBox) June 24, 2012 at 10:58 am #

    I found a site to learn JavaScript, I got stuck there cause of their point-system. Collecting points is my weakness! haha

    http://www.codecademy.com/

    • Natasha Murashev June 24, 2012 at 11:42 am #

      Haha… I was playing on there yesterday myself. The only issue I had was that some of the lessons weren’t well thought out. There doesn’t seem to be much quality control.

      • kjd (@RundBox) June 24, 2012 at 9:51 pm #

        Yea I noticed that too.

        But overall I think that its fun that they have a site with training javascript, html, css and jquery 🙂

  2. Jeffrey Fisher (@jeffSLOfish) October 17, 2012 at 11:07 pm #

    If n is not an integer, you get infinite recursion.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s