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.

FizzBuzz!

I came across a FizzBuzz problem while trying to come up with some sample code.  The problem is pretty simple.

Write a program that prints the numbers from 1 to 100. But for multiples of 3 print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiple of both 3 and 5, print “FizzBuzz”.

Multiple sources said that only 1% of programmers could solve this problem.  That makes me think too many people call themselves programmers.

It took me about 10 minutes to come up with this in javascript:


for (var i=1; i <=100; i++) {
   var x = '';
   if (!(i%3)) {
      x += 'Fizz';
   }
   if (!(i%5)) {
      x += 'Buzz';
   }
   if (x.length == 0) {
      x = i;	
   } 
   document.write(x + "<br>");
}

That worked great.  You can see it at CodePen.  After I finished, I looked at some other answers and found a couple of ways to improve it.  Initially, I wanted to else if all the way through my options, but I had a brainfart and didn’t think of checking if it is divisible by 15.  You can also check to see if x is null and if it is, write i, but I didn’t want to do it that way.  Here is the final code (CodePen):


for (var i=1; i <=100; i++) {
    var x = '';
    if (!(i%15)) {
      x = 'FizzBuzz';
    } else if (!(i%3)) {
      x = 'Fizz';
    } else if (!(i%5)) {
      x = 'Buzz';
    } else {
      x = i;	
    } 
 document.write(x + "<br>");
}

I hope you enjoyed that. It was a fun exercise. I’ll probably write one in ColdFusion soon.