Factorial Functions

I went to CoderByte to see what kind of challenges are out there to stay fresh with. There was one about calculating factorials. It goes like this:

Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24. For the test cases, the range will be between 1 and 18 and the input will always be an integer. 

This one was pretty easy. I just set up a loop and ran through the numbers.

function FirstFactorial(num) { 
var f = 1;
for (var i = 1; i <= num; i++) {
f = i * f;
}
return f;
}

After I was done, I saw that the code hint was to use a recursive function. Admittedly, that would be better looking code. It looks something like this:

function FirstFactorial(num) { 
if (num === 0 || num === 1) {
return 1;
} else {
return num * FirstFactorial(num - 1);
}
}

Both functions get the job done.

Fibonacci Sequence

While I was doing quickie problems, I saw someone was asked to show a sample of the Fibonacci Sequence.  This one only took about 3 minutes.  Simple math.

You can sum up the problem as a+b=c, b+c=d, c+d=e, etc for infinity.  For mine, I stopped at 2 million whatever.


var x=0; y=1;
while (x<1000000) {
  var z = x+y;
  x = y; y = z;
  document.write(z + "<br>");
}

Like I said.  Simple math.  You can look at my CodePen and adjust the while loop to make it go higher, if you like.