20210

230
+164  Q:

## What is your solution to the FizzBuzz problem?

See here

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Disclaimer: I do realize this is easy, and I understand the content of the Coding Horror post I just linked to

+2  A:
``````#!C:\Python25\python.exe
for i in range(1,100):
something = False
text = ""
if not (i%3):
text = text + "Fizz"
something = True
if not (i%5):
text = text + "Buzz"
something = True
if not(something):
print i
else:
print text
``````

That was easy-cheesy...

edit: apparently it's "Buzz", not "Bizz".

+3  A:
```                    `<h1>The Fizz Problem</h1><pre><?php    for (\$i=1; \$i<=100; \$i++)    {        \$divBy3 = !(\$i % 3);        \$divBy5 = !(\$i % 5);        if (\$divBy3)        {            print "Fizz";        }        if (\$divBy5)        {            print "Buzz";        }        else if (!\$divBy3)        {            print "\$i";        }        print "\n";    }?></pre>`
```
+9  A:

I know you didn't ask for the shortest, but this is the shortest I know of without rechecking the modulus (in ruby)

``100.times do |i|   value = (i % 3 == 0) ? 'Fizz' : '';   value += 'Buzz' if (i % 5 == 0)   puts value.empty?  ? i : value;end``
-1 for off-by-one error. The [Integer#times](http://www.ruby-doc.org/core/classes/Integer.html#M001141) method iterates from `0..(n-1)`; easy fix is to replace `100.times` with `1.upto(100)`.
0 is falsey, you can drop those `== 0`s. could collapse most of this with interpolation too
+61  A:

The only real challenge here is turning it in a golf match.

Updated. Now 70 characters in Ruby, 8 characters behind Perl:

``````1.upto(100){|i|a,b=[:Fizz][i%3],[:Buzz][i%5];puts a||b ? "#{a}#{b}":i}
``````

Allowing concatenation (+) for symbols and nil, e.g. (nil + :foo == 'foo', nil + nil == '') would help us a lot. We can monkeypatch Ruby to support this:

``````class Symbol
def +(other)
to_s + other.to_s
end
end

class NilClass
def +(other)
other.to_s
end
end
``````

Now we're down to 58 characters, not counting the monkeypatch, 4 less than Perl:

``````1.upto(100){|_|s=[:Fizz][_%3]+[:Buzz][_%5];puts s!=''?s:_}
``````

Updated. I found the best Ruby solution in comp.lang.ruby. 56 characters, but using `?d` for `100` is sinking pretty damn low, IMHO.

``````1.upto(?d){|i|i%3<1&&x=:Fizz;puts i%5<1?"#{x}Buzz":x||i}
``````

Which language features (that we cannot add by monkeypatching) would make this even shorter?

• an implicit variable (_) for blocks (Perl has this)
• the empty string evaluating to false (Perl has this. Zero (0) too is false.)

With these features, fizzbuzz would look like this (46 characters):

``````1.upto(100){puts [:Fizz][_%3]+[:Buzz][_%5]||_}
``````

@lbrandy: golfscript is very cool. I got fizzbuzz down to 43 characters, but there's definitely room for improvement:

``````101,(;{\..3%'''Fizz'if\5%'''Buzz'if+\or}%n*
``````

Updated. I've got it down to 37 characters, lbrandy, building on your solution (which is 40 characters, incidentally). You can save two characters by replacing `<1` by `!`, twice. And another one by creating an 0..99 array and incrementing the number in the loop, instead of creating a 0..100 array and throwing away the first element.

``````100,{)..3%!'Fizz'*\5%!'Buzz'*+\or}%n*
``````

Amazing what you can do with 36 primitives and 4 datatypes! A new addiction is born.

"using ?d for 100 is sinking pretty damn low, IMHO." - and it doesn't work on Ruby 1.9. ?d now evaluates to "d". ;)
+1  A:

Glad to post the first response in C ;)

``int main(int argc, _TCHAR* argv[]){    for(int i = 0; i < 100 ; i++)    {       if(i%3)        {            if(i%5)            {                printf("FizzBuzz");            }            else            {                printf("Fizz");            }        }       else if(i%5)        {            printf("Buzz");        }    }    return 0;}``
You forgot to printf("%d", i) in case it's not divisible by either.
oh boy... not only is this inefficient because you check for divisibility of 5 twice...but it's wrong! (i%5) isn't non-zero when i is divisible by 5, (i%5) == 0 is the check you need. Terrible.
Super broken. -1
+7  A:

C#...

``            for (int i=1; i<=100; i++)            {                if ((i%3==0) && (i%5==0))                {                    Console.WriteLine("FizzBuzz");                }                else if (i%3 == 0)                {                    Console.WriteLine("Fizz");                }                else if (i%5 == 0)                {                    Console.WriteLine("Buzz");                }                else                {                    Console.WriteLine(i.ToString());                }            }``
i'm fairly sure that that's pretty much the code i wrote... Strange huh?
+4  A:

Not the first way I would choose to do it but you could do the following

and now in vb.net... (for a change)

``For i As Integer = 1 To 100        Select Case True            Case (i Mod 3 = 0) AndAlso (i Mod 5 = 0)                Console.WriteLine("FizzBuzz")            Case i Mod 3 = 0                Console.WriteLine("Fizz")            Case i Mod 5 = 0                Console.WriteLine("Buzz")            Case Else                Console.WriteLine(i.ToString())        End Select    Next``
+1  A:

PHP:

``for ( \$n=1, \$m3=0, \$m5=0; \$n <= 100; \$n++, \$m3=\$n%3==0, \$m5=\$n%5==0 ){   echo \$m3 || \$m5 ? (\$m3 ? 'Fizz' : '') . (\$m5 ? 'Buzz' : '') : \$n;}``
+8  A:

Ok, just for grins, here it is in JavaScript:

``````for(i = 1; i <= 100; i++){
var fizz = (i % 3 == 0);
var buzz = (i % 5 == 0);
var output = "";

//if number is not divisible by 3 or 5, output number
if(!fizz && !buzz){
output = i;
}else{
//if number is divisible by 3, output Fizz
if(fizz){
output = "Fizz";
}

//if number is divisible by 5, add Buzz to output
if(buzz){
output += "Buzz";
}
}

document.write(output + "<br />");
}
``````

There's about a billion different ways to do this...

Way #567,895,670 ("no loops, no ifs" version):

``````document.write(
new Array(8)
.join("001021001201003")
.substr(0, 100)
.replace(
/\d/g,
function (s, i) {
return [ i + 1, "Fizz", "Buzz", "FizzBuzz" ][s] + "<br/>";
})
);
``````
Funny". I was just taking a Javascript [tutorial](http://eloquentjavascript.net/chapter2.html) and decided to cobble up a version of FizzBuzz since this topic was still fresh on my mind. Long story short, it's almost identical to your solution ![:)](http://www.w3.org/Icons/basic/smiley.gif)
lol, yep, this solution is pretty much the basic bare-bones solution...
+6  A:

Alright, here's an example of a one line python FizzBuzz using a list comprehension. It takes advantage of pure boolean logic in place of any control structure. I did it purely to see if I could.

``#!/bin/python#FizzBuzz with an unpythonic List Comprehensionprint [(((not i%3 and not i%5) * 'FizzBuzz') or ((not i%3) * 'Fizz') or ((not i%5) * 'Buzz') or i) for i in range(1,101)]``
+12  A:

Another python. It won't win the golf match, but it uses the least amount of loops/instructions.

``#!C:\Python25\python.exeprint """1\n2\nFizz\n4\nBizz\nFizz\n7\n8\nFizz\nBizz11\nFizz\n13\n14\nFizzBizz\n16\n17\nFizz\n19\nBizzFizz\n22\n23\nFizz\nBizz\n26\nFizz\n28\n29\nFizzBizz31\n32\nFizz\n34\nBizz\nFizz\n37\n38\nFizz\nBizz41\nFizz\n43\n44\nFizzBizz\n46\n47\nFizz\n49\nBizzFizz\n52\n53\nFizz\nBizz\n56\nFizz\n58\n59\nFizzBizz61\n62\nFizz\n64\nBizz\nFizz\n67\n68\nFizz\nBizz71\nFizz\n73\n74\nFizzBizz\n76\n77\nFizz\n79\nBizzFizz\n82\n83\nFizz\nBizz\n86\nFizz\n88\n89\nFizzBizz91\n92\nFizz\n94\nBizz\nFizz\n97\n98\nFizz"""``
i dont think thats quite right.. but i agree.. it does give the correct output.. :) +1
Wrong. It's 'Buzz', not 'Bizz'
the interviewer just asked you to change it to 1 to 1000.
It's OK, I inform the interviewer that in the real world, the spec doesn't change all willy-nilly like that. He'll disagree, but I'll call him a communist and he is forced to hire me to keep up a patriotic status. This does not work in every country.
That's not nearly as difficult to fix as you make it out to be Jian. Now if he wanted it to skip numbers...
Pre-computation is the most computationally sound way to do this. I'm sure there's some C++ pre-compiler nonsense which can be configured to produce output of variable rate like this. If not, you run all your source code through some precompiler/parser/whatever and generate N entries. For embedded systems with low processing power and ample memory, this would be a viable solution, assuming you stored the data more logically.
+1  A:

My rough version in PHP

``````<?php
foreach(range(0, 100) as \$num) {
if(is_int(\$num/3) && is_int(\$num/5)) {echo "FizzBuzz"}
elseif(is_int(\$num/3)) {echo "Fizz";}
elseif(is_int(\$num/5)) {echo "Buzz";}
else {echo \$num;}
}
?>
``````
+6  A:

Can't beat the golf champ but a short c# version (115 chars):

``for (int i = 1; i < 101; i++) {Console.WriteLine(((i % 3) + (i % 5) == 0 ? "FizzBuzz" : (i % 3 == 0 ? "Fizz" : (i % 5 == 0 ? "Buzz" : i.ToString())))); }     ``
+3  A:

Going golfing... 70 characters in Perl:

`for(1..100){print \$_%3?(\$_%5?\$_:'Buzz'):(\$_%5?'Fizz':'FizzBuzz'),"\n"}`
and 25 of those characters required the Shift key
+102  A:

The author asked for a language agnostic solution and so I will attack the question with pseudocode! We could argue about efficency all day but I find this the most readable form.

``````
for every integer 1 to 100
if the integer is divisible by 3 and divisible by 5
print "FizzBuzz"
else if the integer is divisible by 3
print "Fizz"
else if the integer is divisible by 5
print "Buzz"
else
print the integer

``````
Best way to do it ... let the language compiler/interpretter optimize.Definitely the best way to do it.
nah. Prakash has it correct. the method here checks divisibility by 3 more often then necessary.
It feels so much like Python, whoa.
could this not be condensed slightly by checking for divisible by 15 instead of by 3 and 5? It's also more likely to be divisible by 3 than 5 and 5 than 15, so reordering the ifs/elses should make it more efficient.
For what it's worth, I wrote an interpreter that runs this code: http://www.moserware.com/2008/08/meta-fizzbuzz.html
+1  A:
``````#define p printf
int main() {
int i;
for (i = 0; i < 100; i++) {
(i % 3) == 0 ? p("%d=Fizz", i) : p("%d=", i);
(i % 5) == 0 ? p("Buzz\n") : p("\n");
}
return 0;
}
``````

122 characters.

i do not think you are supposed to print 3=Fizz.. it clearly says 'But for multiples of...' which means dont write the number in that case.
+2  A:

In Scheme:

``````(define (fizz n)
(cond ((= 1 n) `(1))
((= 0 (modulo n 15)) (append (fizz (- n 1)) '("FizzBuzz")))
((= 0 (modulo n 5)) (append (fizz (- n 1)) '("Buzz")))
((= 0 (modulo n 3)) (append (fizz (- n 1)) '("Fizz")))
(else (append (fizz (- n 1)) (list n)))))
``````
In Common Lisp, the definition starts with `(defun fizz (n) ...`, `modulo` is called `mod`, and instead of `else`, `t` would be used. Also, usually you would use an apostrophe instead of backticks for quoting in this case, but I think that both work.
+32  A:

Code golf it is. Python. 58 characters. No monkey-patching required :P. Woo.

``i=0;exec"i+=1;print(i%5<1)*'fizz'+(i%3<1)*'buzz'or i;"*100``

edited: to 72

edited: to 58, incorporating an idea from http://stackoverflow.com/questions/437/#2186 (@PabloG, <1 works better than 'not')

+14  A:
``````while(\$i++<100)echo((\$j=(\$i%3?"":"Fizz").(\$i%5?"":"Buzz"))?\$j:\$i)."
";
``````

PHP, 72 characters. Yes, that is a literal newline.

(many edits happened, didn't track them all!)

You can save 4 more characters by removing the quotes around Fizz and Buzz
+1 for saving a char with the newline.
+5  A:

Here's 62 in Perl and I'm not even good at perl. I'm sure Perl golfer could do better.

``````print"\$_\n"for map{(\$_%3?"":"Fizz").(\$_%5?"":"Buzz")||\$_}1..100
``````

edit: added 1 char to go to 100, not 99

+48  A:
Alas, your version does not work
It works. You have to put the cursor on cell B1, then use the drag handle to drag all the way down to B100.
You can remove the dependency on column A by replacing each instance of `A1` with `ROW()`. (Which does make the formula longer, but I'd argue that requiring only one column makes the "solution" shorter.)
@Daniel 'yar' Rosenstark your logic is backwards; MOD will return a non-zero if there is a remainder (not evenly divisible). Furthermore, the rest of the equation would have to deal with writing the numbers in, which you might have to resolve by having a divisible-by test in the conditional, then the what-to-display-when-divisible-by as one of the arguments.
@Nick T, you're right. Here's the OpenOffice fixed version: `=IF(NOT(MOD(A1;3)); "fizz";"") 5)); "buzz";"")`. About writing the numbers in, I assume that you just make a column with `A1+1` in A2 and then just copy and paste it to 100.
@Nick T good point, I think we've got this problem whipped :) Thanks again, I didn't even know my solution from a year ago was backwards due to the stackoverflow-didn't-have-twitter-style-notification-back-then-or-at-least-people-didn't-always-use-it problem.
+38  A:

Assuming I were doing this for an interview, I don't think I'd try to show off by cutting down on the number of lines. I'd try to make my answer as clean and simple as possible. In C#,

``foreach (int number in Enumerable.Range(1, 100)) {    bool isDivisibleBy3 = (number % 3) == 0;    bool isDivisibleBy5 = (number % 5) == 0;    if (isDivisibleBy3)         Console.Write("Fizz");    if (isDivisibleBy5)         Console.Write("Buzz");    if (!isDivisibleBy3 && !isDivisibleBy5)         Console.Write(number);    Console.WriteLine();}``
FYI: Enumerable.Range requires linq
In an interview, I'd consider `Enumerable.Range` to be way overkill. Plain old `for (int i = 1; i <= 100; ++i)` is sufficient!
Uh... this "clean and simple" code is very readably *incorrect*, as it does not print "FizzBuzz" for numbers divisible by 15.
@ShreevatsaR - Yes it does - it's using Console.Write, which appends to the current line until the user uses a WriteLine. So if divisible by 15, it writes "Fizz", then "Buzz", *then* a newline.
I would argue then that this isn't as clean and simple as possible, if by simple at least you mean easy to understand.
Agree with Joren, it works but that optimisation on fizz buzz over 2 lines is ugly.
+5  A:

@Michiel de Mare

Which language features (that we cannot add by monkeypatching) would make this even shorter?

At the risk of going a bit off-topic, here are some:

1. Extremely aggressive type coercion (with high levels of automagic)
2. Stack based
3. High level operations (map, join, rotate, split, sort, 'every ith element', etc.)
4. For #3, using single characters for all of them :)

Taken from golfscript which was a language invented precisely for this purpose.

Updated: @Michiel de Mare ... my golfscript version. 39 characters. Programming in this hurts my brain. I'm sure you could do better, though. It works on the same principle as my 58 character python one. Essentially do a n%3<1 and multiply that by fizz (similar for buzz). Add those. And then or the result with the number. So a null string will be replaced by the number.

``101,(;{..3%1<'fizz'*\5%1<'buzz'*+\or}%n*``

You can see "top" scores for diff. languages here: http://www.shinh.org/p.rb?FizzBuzz. The best golfscript is 37 versus my 39. The best python is 56 vs my 58. And the best ruby is 56 (with no monkey patching :P).

+3  A:

Java... takes a command line arg for max value to run until, if not supplied uses 100

``package stuff.fizzbuzz;public class FizzBuzz {    public static void main(String[] args){        int max=100;        if(args.length>1){print("usage: FizzBuzz <maxCount>");System.exit(0);}        if(args.length==1)max = Integer.valueOf(args[0]).intValue();        for(int i=1;i<=max;i++){            boolean modThree = i%3==0;            boolean modFive = i%5==0;            if(modThree)print("Fizz");            if(modFive)print("Buzz");            if(!modThree&&!modFive)print(i);            println();        }       }    private static void print(String s){System.out.print(s);}    private static void print(int i){System.out.print(i);}    private static void println(){System.out.println("");}}``
+263  A:

Golfing is easy. How large can you make it?

Enterprise FizzBuzz is written in C# and weighs in at 12 classes and 3 interfaces (not including the main program driver). It comes with a suite of unit tests written in MbUnit. It's fairly loosely coupled but I really should update it for C# 3.5.

We need a mod-up for "funny", like /.. :)
Hahaha. This still makes me laugh. I'm thinking I might put together a team to do an updated version. Something where the whole FizzBuzz Enterprise solution can be reconfigured from an XML file or something
...Your own joke still makes you laugh?
It is no less funny today than it was when I wrote it. It is consistently in the top 5 posts that bring traffic to my site as well. Actually that last point is almost depressing.
That is the most beautiful thing I've seen all week!
Well sure it has unit tests, but have you load tested it? Who knows how many users might want to FizzBuzz simultaneously -- and then where would you be?
Sick. +1 for ya! Still, I am surprised you haven't implemented a client-server architecture, with load sharing as suggested by John.
@Sylverdrag - I've ordered a whiteboard but it hasn't arrived yet
@Wolf: Have you integrated an Enterprise Service Bus into it yet? I'm afraid that if you don't, I will have to threaten a fork.
Can you give me a ballpark estimate for porting to J2EE?
Oooh ESB and J2EE sound like awesome ideas. I'll set up the BizTalk server
Sometimes everything that's wrong in the world isn't actually funny at all.
And what about logging? When something goes wrong in production good logs will save you. I suggest log4net logging to a DB backend.
Oh, and internationalization. How do you handle users in a different language?
@Cameron that is *so* true.
He laughs because he is legend.
You are hereby given notice that you violate my patents on both fizzing and buzzing.
This makes me feel *very* sick ...
Where's the factory pattern?
Hahah, I just came across this! Hilarious :D
This is brilliant.
This project is why YAGNI was created. This one specifically.
@Cameron MacFarland: Well, you don't want to have logging cluttering the code, I suggest creating a separate assembly with PostSharp aspects for logging and potentially error handling as well (maybe even the internationalization).
+6  A:

Here's a Delphi/Pascal version:

``var  I: Integer;begin  for I := 1 to 100 do    if (I mod 3 = 0) and (I mod 5 = 0) then      WriteLn('FizzBuzz')    else if I mod 3 = 0 then      WriteLn('Fizz')    else if I mod 5 = 0 then      WriteLn('Buzz')    else       WriteLn(IntToStr(I));end.``
+3  A:

C++ (first post !)

``#include <iostream>int main (int argc, char* argv[]){    int threeRem;    int fiveRem;    for (int i = 1; i <= 100; i++)    {        threeRem = i % 3;        fiveRem = i % 5;        if (fiveRem == 0 && threeRem == 0)            std::cout << "FizzBuzz" << std::endl;        else if (threeRem == 0)            std::cout << "Fizz" << std::endl;        else if (fiveRem == 0)            std::cout << "Buzz" << std::endl;        else             std::cout << i << std::endl;               }    return(0);   }``
+3  A:

Python, modifying slightly from akdom

``````print[(((not i%3)*'Fizz')+((not i%5)*'Buzz')) or i for i in range(1,101)]
``````

73 characters and still pritty legible!

``````print["Fizz"*(i%3<1)+"Buzz"*(i%5<1)or i for i in range(1,101)]
``````

Down to 62 and more legible now (thx @lbrandy)

+1  A:

Of course for runtime speed, you want a lookup table: in C++

``enum fbType {num,fizz,buzz,fizzbuzz};fbType FizzArray[100]{num,num,fizz,num,buzz,fizz,num,num,fizz,buzz <snip large array>,fizz,buzz}int count=0;while (count < 100){    switch(FizzArray[count++])    {     case fizz:          std::cout << "Fizz" << std::endl;          break;     case buzz:          std::cout << "Buzz" << std::endl;          break;     case fizzbuzz:          std::cout << "FizzBuzz" << std::endl;          break;     default:          std::cout << count << std::endl;    }}``
+27  A:

From the Perl monks ( modified to take advantage of Perl 5.10's "say" :-)

`say+(Fizz)[\$_%3].(Buzz)[\$_%5]||\$_ for 1..100`

44 chars.

I don't see a way to golf it any further, but you could use "map{say+(Fizz)[\$_%3].(Buzz)[\$_%5]||\$_}1..100" if you wanted to get rid of that annoying whitespace. ;)
+1  A:

@Pat

I can't believe that works. I don't have a new enough version of perl to try it. It appears to contain some seriously hilariously auto-black-magic. Like I presume you have a list with 'fizz' that you are indexing based on the mod directly and this index is allowed to be out of range?

As far as golfed Perl goes, I think it's remarkably clear. Your presumption is correct. Indexing an array out of bounds returns undef, which stringifies to ''
+1  A:

@lbrandy

This slightly longer version works with older versions of Perl, it is the same except it uses print with \n instead of "say" so you can easily test it.

`print+(Fizz)[\$_%3].(Buzz)[\$_%5]||\$_,\$/for 1..100`

You are right, when the index [\$%3] is zero the expresstion (Fizz)[\$%3] evaluates to the first (and only) element Fizz , when the index is any any other value the index is out of range and the expression evaluates to undef.

@Michiel de Mare

I know this is only half serious, but what is the point of monkeypatching a few functions in a golf match context? You could monkeypatch in the fizzbuzz function itself and just call

`100.fb`

or even

`1.f`

Three chars of ruby code (not counting the monkeypatch :-)

+9  A:

C#

``````for(int i=1;i<101;i++)
Console.Write("{0: 0;; }{1:;;Fizz}{2:;;Buzz}",i%3*i%5==0?0:i,i%3,i%5);
``````

92 mandatory characters

very nice :) you can even go further (requires a using C=System.Console though) for (var i=1;i<101;C.Write("{0: 0;; }{1:;;Fizz}{2:;;Buzz}", i%3*i%5==0?0:i,i%3,i++%5));
I like it. Btw, you could save one more character with "for(int i=0;++i<101;)"
I had to try and beat 92... Just posted what I think is an 87 char answer. (I plagiarized your use of a format string).
+12  A:

MSIL:

``.assembly extern mscorlib {}.assembly fizzbuzz {.ver 1:0:1:0}.module fizzbuzz.exe.method static void main() cil managed{.entrypoint.maxstack 2.locals init ([0] int32 num,[1] bool divisibleByThree,[2] bool divisibleByFive)//initialize counterldc.i4.1 stloc.0 br.s _checkEndCondition_beginLoop: //Check divisible by threeldloc.0 ldc.i4.3 rem ldc.i4.0 ceq stloc.1 //Check divisible by fiveldloc.0 ldc.i4.5 rem ldc.i4.0 ceq stloc.2 //Check if not divisible by three or fiveldloc.1 brtrue.s _checkDivisibleByThreeldloc.2 brtrue.s _checkDivisibleByThree//Not divisible by three or five, write counterldloc.0 call void [mscorlib]System.Console::WriteLine(int32)br.s _incrementCounter_checkDivisibleByThree: ldloc.1 brfalse.s _checkDivisibleByFiveldstr "Fizz"call void [mscorlib]System.Console::Write(string)_checkDivisibleByFive:ldloc.2 brfalse.s _newLineldstr "Buzz"call void [mscorlib]System.Console::Write(string)_newLine:call void [mscorlib]System.Console::WriteLine()_incrementCounter: ldloc.0 ldc.i4.1 add stloc.0 _checkEndCondition: ldloc.0 ldc.i4.s 0x65blt.s _beginLoopret }``
I've added another answer removing those pesky locals (those who think they are something, but disappears as soon as their protecting stack frame looks the other way), removing a quarter of the instructions, but I had to increase the stack size by 50%. http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/3690208#3690208
+17  A:

And now for something completely different, a solution in Befunge:

``1> :3%#v_"zzif",,,,v  v    <           <  >:5%#v_"zzub",,,,v  v    <           <  >::3%\5%*!#v_:.  v  v**455:,*48<     <  >-#v_@            ^ +1<             ``

Give it a try on using this online interpreter.

Also, this isn't remotely optimized for space, but that's what the edit button's for. :)

I wrote a smaller version but I can't edit yours, so I posted it as a separate answer.
Would you measure the size of a Befunge program in non-whitespace characters or in the dimensions of the program?
Dimensions of the program. Mainly because that's how the ICFP2006 contest measured 2D programs.
Hmm. I tried this in your interpreter but i couldn't get it to work. Maybe i was working it wrong?
I just tried it. Works fine. Did you erase the '@' in the box first?
+1  A:

@Coincoin and Pat: You've set new records for C# and Perl! You should submit them to http://www.shinh.org/p.rb?FizzBuzz and become instantly famous!

+91  A:

And another implementation in one of the underrated programming languages, thanks to some japanese people. And yes, that actually works, just tested it in an IDE.

``````>++++++++++[<++++++++++>-]>>>+++>+++++>+<<<<<<
[
>>>+
>- [<<+>>-]<<<+>[<[-]>>>+<<-]<[>>>+++>>[-]<<<<<- +++++++[>++++++++++<-]>.<+++++++[>+++++<-]>.<++++[>++++<-]>+..[-]<]>>
>>- [<<<+>>>-]<<<<+>[<[-]>>>>+<<<-]<[>>>>+++++>[-]<<<<<- +++++++++++[>++++++<-]>.<+++++++[>+++++++<-]>++.+++++..[-]<]>>
>>>
[-
<<<[<+>>>>+<<<-]<[>+<-]>>>>
[
>++++++++++<
[>-[>+>+<<-]>[<+>-] +>[<[-]>-]< [>>+<<<++++++++++>-]<<-]
>---------- >>>[<<<<+>>>>-] <<<<
>>>>>+> >>[-] <[>+<-] <[>+<-] <<<<< [>>>>>+<<<<<+] <
]
>>>>>
[ <++++++[>>++++++++<<-]>> . [-] >[<+>-] >[<+>-] <<<-]
<<<<<
]+
<<<<<
+++++++++++++.---.[-]
<-]
``````
Funniest response I've read in a long time.
you sir... you... are damaged!
For some reason I thought you meant that BF was underrated because of some Japanese people, so your link was disappointingly juiceless. ;)
Haha, after reading it again I have to say you're right. Note to self: Less commas, more sentences.
I think this is in fact a cleverly disguised Whitespace program :D
+7  A:

Here's how I did it in Groovy (69 chars), but somehow someone did this in 57 chars:

``(1..100).each{s=(it%3?"":"fizz")+(it%5?"":"buzz");println s==""?it:s}``
+2  A:

@Geocoin: If you're going to say "runtime speed", then say it like you mean it: using `endl` (write newline + force flush) is almost certain to make your program even more I/O-bound than it already is, and makes whatever other optimisations you have totally irrelevant.

Moral of the story: `cout << endl` is not the same as `cout << '\n'`. Only use `endl` if you actually require your output to be flushed at that point. Here's an article by Scott Meyers (author of the Effective C++ series) that says it much better than I can. :-)

NOTE: it was my understanding that cout will, by default, inject a flush for you when it interpets the '\n' literal.
+12  A:

``````intToString i | i `mod` 15 = "FizzBuzz"
| i `mod` 3 = "Fizz"
| i `mod` 5 = "Buzz"
| otherwise = show i
main = mapM_ (putStrLn . intToString) [1..100]
``````
+1  A:

Simple python:

``for i in range(1,101):    if (i % 5 == 0) and (i % 3 == 0):        print "FizzBuzz"        continue    if i % 3 == 0:        print "Fizz"        continue    if i % 5 == 0:        print "Buzz"        continue    print i``
+1  A:

Too bad I don't have any C compiler installed at the moment. I'm sure I'd mention that if I wanted a bit of easy performance but slightly harder to read, I'd change my if ... == 0 to if !(...). That said, here's my best shot w/o a compiler to test it handy:

``````#include "stdio.h"

main()
{
char x = 1;
char cheat = 0;

do
{
cheat = 0;

if x % 3 == 0
{
cheat++;
printf("Fizz");
}

if x % 5 == 0
{
cheat++;
printf("Buzz");
}

if cheat == 0
printf("%i", x);

printf("\n");

x++;
} while x < 100;
}
``````
When has C had a "then" statement? Also, it is customary to #include <stdio.h> instead of "stdio.h". Both should work, but "" searches the current directory first, while <> looks in the system headers.
+2  A:

My Java version:

``import static java.lang.System.out;public class FizzBuzz {    public static void main(String[] args) {        boolean a, b;        for (int i = 1; i <= 100; i++) {            if (a = (i % 3 == 0))                out.print("Fizz");            if (b = (i % 5 == 0))                out.print("Buzz");            if (!a && !b)                out.print(i);            out.println();        }    }}``
+1  A:

I'm still waiting to see the COBOL implementation. :-)

+1  A:

Here is a bunch of solutions in different languages (C, C++, D, Haskell, Lua, OCaml, PHP ...)

+5  A:

t-sql

``````select  case when rn % 3 = 0 then 'Fizz' else '' end
+ case when rn % 5 = 0 then 'Buzz' else '' end
+ case when rn % 3 > 0 and rn % 5 > 0 then cast(rn as nvarchar) else '' end
from
(
select top 100 row_number() over (order by name) rn
from spt_values
) a
``````

edit- I actually had to write this out on Friday at an interview. Didn't use SQL though. For loops are burned into my head better I guess.

+2  A:

This answer isn't perfect in any one dimension, but I like:

• the fact that it has a very low cyclomatic complexity
• that it is pretty readable
• that it handles the most specific case first and the least specific case last.
• that it explicitly handles the "FizzBuzz" case rather than implying it as an overlap of the Fizz and Buzz cases

I'd love some criticism on this!

``````for each integer currentNum from 1 to 100 do
if currentNum modulo 15 is 0 then
print 'FizzBuzz'
else if currentNum modulo 5 is 0 then
print 'Buzz'
else if currentNum modulo 3 is 0 then
print 'Fizz'
else
print currentNum
endif
endfor
``````
i dont like the explicit fizzbuzz case.. i mean why? true it is mentioned as a case in teh problem statement.. but i've always just read that as 'put fizz before buzz' which if you do 3 before 5 it works.. aspecially important if you want to add 7=Bang later
+1  A:
1. Build the output string with any of the algorithms (that work) mentioned by the others
2. Copy the output string to your source code as a constant (too bad if you use Brainfuck)
3. Output the constant

var TheAnswerToFizzBuzz = '1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 9798 Fizz Buzz' // could be wrong :)

why can you not just print the sting? why the variable?
+21  A:

All of you people who are checking to see if the number is divisible by three AND that it is divisible by five will find it more concise to consider whether the number is divisible by fifteen. This isn't rocket surgery. And brevity is the soul of wit.

All you people who are checking divisibility 3 times are doing it wrong to begin with.
All you people who are checking divisibility at all are doing it wrong to begin with.
+1  A:

I just thought I'd correct Mark's elegant C implementation. Excuse me for being a pedant, but it was only printing numbers 1 to 99. Fred's C solution, however, needs quite a bit of work. Fred, which C implementation supports the ``then'' keyword?

``````/* Improvement on Mark's C solution */
#include <stdio.h>
#define p printf
int main() {
int i;
for (i = 1; i <= 100; ++i) {
(i % 3) == 0 ? p("%d=Fizz", i) : p("%d=", i);
(i % 5) == 0 ? p("Buzz\n") : p("\n");
}
return 0;
}
``````

I'm quite sure that this is the first C solution in this thread that will compile and does almost exactly what was requested.

almost yes.. its said to print fizz/buzz instead of teh number.. not as well as
+24  A:

Here is my solution. It is written in 8051 assembly. You will need a 11.0592 MHz quartz to run this thing :p

``````;*** CONSTANTS ***

; divider1
; the first divider's value
divider1 equ 3d

;divider2
; the second devider's value
divider2 equ 5d

; limit
; the maximum value that the fizzbizz program can reach. Must be between 0 and 100
limit equ 100d

;*** CODE ***

; Code segment at 0
cseg at 0
ljmp start ; avoir interrupt vectors
org 0x100 ; and go to a safer place
start: ; a.k.a here.
;
mov scon,#0x52 ; set UART to 8,0,n
mov tmod,#0x20 ; Timer1: autoreload
mov th1,#0xfe ; speed: 9600 bps
setb tr1 ; start Timer1

mov dptr,#intro ; load the intro and...
call emit ; beem it!

mov r7,#0 ; set counter to 0
compute:
cjne r7,#limit,continue ; are we finished with counting to 100?
jmp rest_in_peace ; Yes... rest in peace.
continue:
call do_crlf ; go to next line
mov r4,#1 ; set the (r7%3)? flag
inc r7 ; counter++
mov b,#divider1 ;
mov a,r7 ; divide the counter by three
div ab ;
mov a,b ; and get the reminder
jz do_fizz ; if it is null, do a fizz :)
next:
mov b,#divider2 ;
mov a,r7 ; divide the counter by five
div ab ;
mov a,b ; and get the reminder
jz do_buzz ; if it is null, do a buzz :D
mov a,r4 ; did we do a fizz?
jz compute ; if yes, reume the loop
call write_number ; else, write the number
jmp compute ; and resume the loop

rest_in_peace:
clr tr1 ; Stop Timer1
jmp \$ ; AM STONED!

; do_fizz
; gets: nothing
; returns: 0 in r4
; description:
; Beems a "Fizz" through the UART
do_fizz:
mov dptr,#fizz ; load the fizz
call emit ; then display it
mov r4,#0 ; and leave a message: "I was here"
jmp next ; then resume your normal activity

; do_buzz
; gets: nothing
; returns: nothing
; description:
; Beems a "Bizz" through the UART
do_buzz:
mov dptr,#buzz ; load the buzz
call emit ; then display it
jmp compute ; then resume the loop

; do_crlf
; gets: nothing
; returns: nothing
; description:
; Beems the Carriage return/Line feed controle caracters through the UART.
do_crlf:
mov dptr,#crlf ; load crlf
call emit ; then send it
ret ; and return

; emit
; gets: the adress of the message to display in dptr
; returns: nothing
; description:
; Beems an ASCIIZ message, stored in the code memory, through the UART.
emit:
mov r6,#0 ; initialize the index to 0
bc_1:
mov a,r6 ;
inc r6 ; load the pointed byte
movc a,@a+dptr ;
jz fin ; if zero then return
jnb ti,\$ ; if the last transmission isn't over, stay in your place
mov sbuf,a ; and transmit!
clr ti ; and clear ti to get further notifications :p
jmp bc_1 ; end of the loop
fin:
ret ; return

; emit_id
; gets: the digit's value in A (must be between 0 and 9)
; returns: nothing
; description:
; Translates a one-digit-bcd value located in A into Ascii and the beems it through the
; UART.
emit_id:
mov r5,a
mov a,#'0'
jnb ti,\$
mov sbuf,a
clr ti
ret

; write_numer
; gets: the number to display in r7
; returns: nothing
; description:
; Beems the Ascii representation of the number located in r7 through the UART. r7 must
; be between 0 and 99
write_number:
mov a,r7 ;
mov b,#10d ; divide the number by 10
div ab ;
jz write_l ; if it si less than 10 then just write the modulo
call emit_id ; else, write the result (because r7<100) :)
write_l:
mov a,b ; prepare the parameters
call emit_id ; and send the digit
ret ; then return

; *** STATIC DATA ***

; fizz
; type: Asciiz string
; description:
; containes the fizz message
fizz: db "Fizz",0

; buzz
; type: Asciiz string
; description:
; containes the buzz message
buzz: db "Buzz",0

; intro
; type: Asciiz string
; description:
; contains the intro message.
; P.S:
; intro shares it's Asciiz 0 with crlf, 3 code bytes of economy :)
intro: db "The FizzBuzz test"

; crlf:
; type: Asciiz string
; description:
; containes the crlf byte couple
; P.S:
; shares itself and it's Asciiz 0 with intro
crlf: db 10,13,0

; Bye Bye :)
end
``````
good lord that is long!
Some interesting things going on there with the syntax coloring.
@Karl - That's what she said... (Sorry...)
@ChaosPandion: Never apologize for thats what she said!
+49  A:

My Ook. is a bit rusty, and I don't have a compiler on hand to check it, but I believe this works:

``````### FizzBuzz in Ook.
Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook.
Ook. Ook. Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook?
Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook.
Ook. Ook.
Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook.
Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook? Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook? Ook! Ook! Ook! Ook? Ook? Ook. Ook? Ook.
Ook. Ook. Ook. Ook? Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook? Ook.
Ook. Ook. Ook. Ook? Ook! Ook? Ook? Ook. Ook! Ook? Ook! Ook!
Ook? Ook! Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook.
Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook?
Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook.
Ook? Ook. Ook? Ook.

Ook? Ook. Ook! Ook! Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.

Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook!
Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook?
Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook. Ook! Ook. Ook! Ook.
Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook?
Ook. Ook? Ook! Ook! Ook! Ook? Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook?
Ook. Ook? Ook. Ook? Ook! Ook! Ook? Ook!
Ook? Ook. Ook? Ook. Ook? Ook.
Ook? Ook.
Ook. Ook. Ook. Ook? Ook! Ook? Ook? Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook!
Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook!
Ook? Ook. Ook? Ook.
Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook. Ook? Ook.
Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook?
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook.
Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook! Ook. Ook. Ook.
Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook!
Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook?
Ook! Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook!
Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook!
Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook? Ook. Ook! Ook? Ook. Ook? Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook?
Ook. Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook?

Ook! Ook? Ook? Ook.
Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook. Ook. Ook. Ook? Ook! Ook? Ook? Ook.
Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook?
Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook!
Ook! Ook! Ook! Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook? Ook? Ook. Ook? Ook.
Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook!
Ook? Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook? Ook! Ook!
Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook!
Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook.
Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook?
Ook. Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook.
Ook. Ook. Ook? Ook! Ook? Ook. Ook? Ook! Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook?
Ook. Ook? Ook! Ook? Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook? Ook.
Ook! Ook! Ook? Ook!
Ook. Ook? Ook. Ook? Ook! Ook. Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook?
Ook? Ook. Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook? Ook? Ook.
Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook!
Ook? Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook.
Ook? Ook. Ook? Ook! Ook. Ook.
Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook.
Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook.
Ook. Ook. Ook. Ook. Ook! Ook. Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook. Ook! Ook?
Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook! Ook? Ook!
``````
"I don't have a compiler on hand to check it", Ha.
You should have commented on your block with this:"Beware of bugs in the above code; I have only proved it correct, not tried it"
Nice reference, prestomation!
http://bluesorcerer.net/esoteric/ook.html The C# interpreter says Syntax error!
+1  A:
``````int main()
{
int i;
for(i=1;i<=100;i++)
printf({"%d\n", "Fizz", "Buzz", "FizzBuzz"}[(!(i%3))+2*!(1%5)],i);
return 0;
}
``````

That's C but with 2 edits it also works in D or with an include, C++

+3  A:

I happened to be using this exercise to learn Lua:

``````for n=1,100 do
if n%3==0 and n%5==0 then
print("FizzBuzz")
elseif n%3==0 then
print("Fizz")
elseif n%5==0 then
print("Buzz")
else
print(n)
end
end
``````
+8  A:
Wrong! This doesn't print out the numbers 1, 2, 4, 7, 8...! You're gonna need to change your line numbers! (or maybe you can just use a couple of additional GOTOs instead) :)
+2  A:
+5  A:

Powershell:

``````0..100 | %{
if (!(\$_ % 3)){
if(!(\$_ % 5)){"FizzBuzz"}
"Fizz"
}elseif(!(\$_ % 5)){"Buzz"}
else{\$_}
}
``````
+3  A:

Another JavaScript solution (110 characters) :)

``````f='Fizz';b='Buzz';for(i=1;i<101;i++){sOut=(i%15==0)?f+b:((i%3==0)?f:((i%5==0)?b:i));document.write(sOut+" ");}
``````
+1  A:
``````for every integer 1 to 100
if the integer is divisible by 3
print "Fizz"
end if
if the integer is divisible by 5
print "Buzz"
end if
print newline
end for
``````

I believe this also works, and it's simpler than the pseudocode given in the currently accepted answer.

One should also print out the integer, in the cases where it is not a fizz and it is not a buzz.
+1  A:

Here is Fizz Buzz in IL:

``````.method public hidebysig static void FizzBuzz() cil managed
{
.maxstack 2
.locals init (
[0] bool fizz,
[1] bool buzz,
[2] int32 i,
[3] bool CS\$4\$0000)
L_0000: nop
L_0001: ldc.i4.1
L_0002: stloc.2
L_0003: br.s L_0051
L_0005: nop
L_0006: ldloc.2
L_0007: ldc.i4.3
L_0008: rem
L_0009: ldc.i4.0
L_000a: ceq
L_000c: stloc.0
L_000d: ldloc.2
L_000e: ldc.i4.5
L_000f: rem
L_0010: ldc.i4.0
L_0011: ceq
L_0013: stloc.1
L_0014: ldloc.0
L_0015: ldc.i4.0
L_0016: ceq
L_0018: stloc.3
L_0019: ldloc.3
L_001a: brtrue.s L_0027
L_001c: ldstr "Fizz"
L_0021: call void [mscorlib]System.Console::WriteLine(string)
L_0026: nop
L_0027: ldloc.1
L_0028: ldc.i4.0
L_0029: ceq
L_002b: stloc.3
L_002c: ldloc.3
L_002d: brtrue.s L_003a
L_002f: ldstr "Buzz"
L_0034: call void [mscorlib]System.Console::WriteLine(string)
L_0039: nop
L_003a: ldloc.0
L_003b: brfalse.s L_0040
L_003d: ldloc.1
L_003e: br.s L_0041
L_0040: ldc.i4.1
L_0041: stloc.3
L_0042: ldloc.3
L_0043: brtrue.s L_004c
L_0045: ldloc.2
L_0046: call void [mscorlib]System.Console::WriteLine(int32)
L_004b: nop
L_004c: nop
L_004d: ldloc.2
L_004e: ldc.i4.1
L_0050: stloc.2
L_0051: ldloc.2
L_0052: ldc.i4.s 100
L_0054: cgt
L_0056: ldc.i4.0
L_0057: ceq
L_0059: stloc.3
L_005a: ldloc.3
L_005b: brtrue.s L_0005
L_005d: ret
}
``````
I think it is Fizz Buzz in Reflector.
+1  A:

Here is Fizz Buzz in Chrome

``````method GlobalApplication.FizzBuzz;
begin
var i: Int32 := 1;
while (i <= 100) do begin
var fizz: Boolean := ((i mod 3) = 0);
var buzz: Boolean := ((i mod 5) = 0);
if fizz then
Console.WriteLine('Fizz');
if buzz then
Console.WriteLine('Buzz');
if not (fizz or buzz) then
Console.WriteLine(i);
inc(i)
end
end;
``````
+1  A:

Here is my version in C#

``````public void FizzBuzz()
{
for (int i = 1; i <= 100; i++)
{
bool fizz = (i % 3) == 0;
bool buzz = (i % 5) == 0;
if (fizz)
{
Console.WriteLine("Fizz");
}
if (buzz)
{
Console.WriteLine("Buzz");
}
if (!(fizz || buzz))
{
Console.WriteLine(i);
}
}
}
``````
+1  A:
``````using System;

class FizzBuzz
{
static void Main(string args[])
{
for(int i = 1; i <= 100; i++)
{
if(i % 15 == 0)     Console.WriteLine("Fizz Buzz");
else if(i % 3 == 0) Console.WriteLine("Fizz");
else if(i % 5 == 0) Console.WriteLine("Buzz");
else                Console.WriteLine(i);
}
}
}
``````
+1  A:

C# Version. Nothing new, just yet another variation.

``````String output;
for (int i=1;i<=100;i++)
{
output = (i % 3 == 0) ? "Fizz" : "";
output = (i % 5 == 0) ? output + "Buzz" : output;
if (output.Equals("")) output = i.ToString();
Response.Write(output + "<br />");
}
``````
+1  A:

Ok, first post on the site. A C++ version, obfuscated of course, with some preprocessor trickery as well.

``````#include <iostream>
#define d(a,z) a z
#define _(a,z) d(#z,#a)
#define b(b) _(b,b)
#define i _(i,f)c
#define u _(u,b)c
#define c b(z)
void main()
{
char t[4];int j=0x30490610;
for(*(int*)t=48;t[2]?0:t[1]?++t[1]==58?t[1]=48,++t[0]==58?t[0]=49,t[1]=t[2]=48:1:1:++t[0]==58?t[0]=49,t[1]=48:1;j=(j>>2)??!((j&3)<<28))std::cout<<(j&3?j&1?j&2?i u:i:u:t)<<'\n';
}
``````

There's also no division or modulo nor conversion from integer to string.

Built using DevStudio 2005.

Skizz

+4  A:

Here it is in Dataflex. (Why did I get to have to program in the unknown language)

``````procedure fizzBuzz
integer i
for i from 1 to 100
if (mod(i,15)) eq 0 showln "fizzbuzz"
else if (mod(i,3)) eq 0 showln "fizz"
else if (mod(i,5)) eq 0 showln "buzz"
else showln i
loop
end_procedure
``````
Hey hey, first occurence of DataFlex on Stack Overflow. I did a lot of DF programming back in the late eighties.
@[vzczc]: @[seanyboy]: i am overcome by a wave of nostalgia - I helped implement dataflex 3.0 in the late eighties/early nineties. I'm glad to see it is still alive ;-)
+14  A:

Python, using list comprehension and the new `x if ... else y` convention.

`["FizzBuzz" if (n % 15 == 0) else "Fizz" if (n % 3 == 0) else "Buzz" if (n % 5 == 0) else n for n in range(1,101)]`

+113  A:

A python solution that uses neither division nor modulus:

``````def div3():
while True:
yield ""
yield ""
yield "Fizz"

def div5():
while True:
yield ""
yield ""
yield ""
yield ""
yield "Buzz"

data = zip(div3(), div5(), range(1, 101))
for (fizz, buzz, value) in data:
print fizz + buzz or value
``````
The "if s:\n\tprint s;\nelse:\n\tprint k[2];" can be shortened to "print s or k[2]" and all semicolons can be dropped.
I took the liberty of editing out the semicolons.
And I took the liberty of editing out the extra prints.
wow really cool!
perhaps "A python solution that uses neither division nor modulus:" would be nicer
Wow this is awesome!
This is my favourite solution so far... :)
Cool! You could make it more compact by using the itertools `cycle` function, allowing e.g. `div5 = cycle([''] * 4 + ['Buzz'])`.
+149  A:

Don't forget lolcode...http://lolcode.com/contributions/cheezburger-fizzbuzz

(Not My Code)

For the clicky impaired:

``````HAI
BTW LOL I HAS A FIZZBUZZ EXAMPLE

CAN HAS STDIO?
I HAS A NUMBAR
LOL NUMBAR R 0

I HAS A MACKSIMUM
LOL MACKSIMUM R 100

IM IN YR LOOPZ
LOL NUMBAR R NUMBAR UP 1

I HAS A NUMBAR_IZ_CHEEZ
LOL NUMBAR_IZ_CHEEZ R 0

I HAS A NUMBAR_IZ_BURGER
LOL NUMBAR_IZ_BURGER R 0

I HAS A COUNTAR
LOL COUNTAR R 0

I HAS A MAX_COUNTAR
LOL MAX_COUNTAR R NUMBAR OVAR 3

IM IN YR LOOP
LOL COUNTAR R COUNTAR UP 1

BTW I CHECKIN FOR CHEEZ LOL
I HAS A CHEEZ_NUMBAR
LOL CHEEZ_NUMBAR R COUNTAR TIEMZ 3
IZ CHEEZ_NUMBAR LIEK NUMBAR?
YARLY
LOL NUMBAR_IZ_CHEEZ R 1
KTHX

BTW I CHECKIN FOR BURGER LOL
I HAS A BURGER_NUMBAR
LOL BURGER_NUMBAR R COUNTAR TIEMZ 5
IZ BURGER_NUMBAR LIEK NUMBAR?
YARLY
LOL NUMBAR_IZ_BURGER R 1
KTHX

IZ COUNTAR BIGR THAN MAX_COUNTAR?
YARLY
GTFO
KTHX
KTHX

IZ NUMBAR_IZ_CHEEZ LIEK 1 AND NUMBAR_IZ_BURGER LIEK 1?
YARLY
VISIBLE "CHEEZBURGER"
NOWAI
IZ NUMBAR_IZ_CHEEZ LIEK 1?
YARLY
VISIBLE "CHEEZ"
NOWAI
IZ NUMBAR_IZ_BURGER LIEK 1?
YARLY
VISIBLE "BURGER"
NOWAI
VISIBLE NUMBAR
KTHX
KTHX
KTHX

IZ NUMBAR UP 1 BIGR THAN MACKSIMUM?
YARLY
GTFO
KTHX
KTHX
KTHXBYE
``````
Hey! This output is ALL WRONG! ...;)
Ouch... my frontal lobes hurt! =)
... I love.... *wants to get a .netlolcompiler
One of my favorite languages :)
LOLcode always makes me laugh
What has the world come to now?!?!??!?!
Really disappointing that SO doesn't have highlighting for this language.
This would be so much easier if lolcode had a modulus. But so much less funny.
+1  A:

My version with QBASIC:

``````FOR i = 1 TO 100
skip = 0
IF i MOD 3 = 0 THEN
PRINT "Fizz";
skip = 1
END IF
IF i MOD 5 = 0 THEN
PRINT "Buzz";
skip = 1
END IF
IF skip = 0 THEN PRINT i;
PRINT
NEXT i
``````
+9  A:

Ruby:

``````require 'rubygems'
require 'fizzbuzz'
puts fizzbuzz
``````

:-D

The FizzBuzz gem is worth reading. It includes a total of 8 solutions, each clever in its own little way.
+3  A:

Since nobody has done anything with a graphing calculator yet, here's my version in TI-BASIC. This was written on a TI-83 Plus graphing calculator which doesn't have a modulus operation built in, hence the use of the fPart function.

``````:For(X,1,100
:1->A
:If 0=3*fPart(X/3:3->A
:If 0=5*fPart(X/5:5A->A
:If A=1:Disp X
:If A=3:Disp "FIZZ
:If A=5:Disp "BUZZ
:If A=15:Disp "FIZZBUZZ
:End
``````

If I am counting them right, the total symbols should be 93. Note that the TI-83 stores some of the program symbols such as "For(" as a single symbol even though it is displayed as four characters.

+3  A:

Or, wearing my software manager hat, my solution would be this:

"Hey, Johnny, can I see you for a second?"

:: Johnny enters ::

"Yes?"

"Go solve FizzBuzz for me, wouldja? You can charge the time to code #94921.228."

or, better yet, just enter a bug into FogBugz:

"FizzBuzz implementation is empty"

and assign it to Johnny.

+1  A:

PHP 1 liner

``````<?php while (++\$i <= 100) echo (!(\$i % 15) ? "fizzbuzz" : (!(\$i % 3) ? "fizz" : (!(\$i % 5) ? "buzz" : \$i))) . "\n"; ?>
``````
+1  A:

Classic VB, 85 chars without white space:

``````f = "Fizz"
b = "Buzz"
For i = 1 To 100
Debug.Print IIf(i Mod 15, IIf(i Mod 3, IIf(i Mod 5, i, b), f), f & b)
Next
``````

Yeah, pretty lame.

+3  A:

Tcl: (assumes \$limit is the upper bound you want to count to)

``````for {set i 0} {\$i < \$limit} {incr i} {
set str ""
if {\$i % 3 == 0} {
append str "FIZZ"
}
if {\$i % 5 == 0} {
append str "BUZZ"
}
if {\$str == ""} {
append str \$i
}
puts \$i
}
``````
+3  A:

SQL Server

``````DECLARE @LoopInt INT
SET @LoopInt =1
WHILE @LoopInt <= 100 BEGIN

PRINT ISNULL(NULLIF(CASE WHEN @LoopInt % 3 = 0 THEN 'Fizz' ELSE '' END
+ CASE WHEN @LoopInt % 5 = 0 THEN 'Buzz' ELSE '' END, ''), @LoopInt)

SET @LoopInt= @LoopInt + 1
END
``````
+1  A:

perl -e'foreach \$x ( 1 .. 100) { if( \$x % 3 == 0 ) { print "Fizz"; } if( \$x % 5 == 0 ) { print "Buzz"; }unless ( \$x % 3 == 0 || \$x % 5 == 0 ) { print "\$x" } print "\n"; }'

Works, but could probably stand more obfuscation.

+3  A:

An F# solution is as follows:-

Edit: Modified to compile under F# 1.9.6.0 latest CTP.

```#light

let inline (/%) x y = x % y = 0
let fb = function
| x when x /% 15 -> "FizzBuzz"
| x when x /% 3  -> "Fizz"
| x when x /% 5  -> "Buzz"
| x              -> x.ToString()

[1..100] |> List.map (fb >> printfn "%s")
```

For some reason the context highlighter seems to go crazy with this one so I used pre tags instead!

I would probably use `List.iter` over `List.map` unless you really want to produce a new list of 100 copies of `unit`
+35  A:

Sorry. I couldn't resist.

```IDENTIFICATION DIVISION.
PROGRAM-ID.  FIZZBUZZ.

DATA DIVISION.

WORKING-STORAGE SECTION.

01 WS-FIZZBUZZ-ITEMS.
05 WS-FIZZBUZZ-ITERATION-COUNTER      PIC 9(003).
05 WS-FIZZBUZZ-DIVISION.
10 WS-FIZZBUZZ-QUOTIENT            PIC 9(003).
10 WS-FIZZBUZZ-REMAINDER           PIC 9(003).
05 WS-FIZZ-CHECKS.
10 WS-FIZZ-CHECK                   PIC X(004)   VALUE SPACES.
88 SW-FIZZ-IS-TRUE                           VALUE "FIZZ".
88 SW-FIZZ-IS-NOT-TRUE                       VALUE SPACES.
10 WS-BUZZ-CHECK                   PIC X(004)   VALUE SPACES.
88 SW-BUZZ-IS-TRUE                           VALUE "BUZZ".
88 SW-BUZZ-IS-NOT-TRUE                       VALUE SPACES.
10 WS-NUMERIC-CHECK                PIC X(004)   VALUE SPACES.
88 SW-NUMERIC-IS-TRUE                        VALUE "NUMERIC"
88 SW-NUMERIC-IS-NOT-TRUE                    VALUE SPACES.
05 WS-FIZZBUZZ-RECORD
10 WS-FIZZBUZZ
15 WS-FIZZ                      PIC X(004).
15 WS-BUZZ                      PIC X(004).
10 WS-NUMERIC                      PIC 9(004).

PROCEDURE DIVISION.
0100-PERFORM-FIZZBUZZ.
PERFORM VARYING WS-FIZZBUZZ-ITERATION-COUNTER FROM 1 TO 100 BY 1
PERFORM 0150-INITIALIZE-VARIABLES
PERFORM 0160-INITIALIZE-SWITCHES
PERFORM 0200-CHECK-NUMERIC-FOR-FIZZ
PERFORM 0210-WRITE-FIZZ
PERFORM 0300-CHECK-NUMERIC-FOR-BUZZ
PERFORM 0310-WRITE-BUZZ
PERFORM 0400-CHECK-NUMERIC-FOR-NUMERIC
PERFORM 0410-WRITE-NUMERIC
PERFORM 0500-DISPLAY-RECORD
STOP RUN
.

0150-INITIALIZE-VARIABLES.
MOVE ZEROES TO WS-FIZZBUZZ-ITERATION-COUNTER
MOVE ZEROES TO WS-FIZZBUZZ-DIVISION
MOVE SPACES TO WS-FIZZ
MOVE SPACES TO WS-BUZZ
MOVE ZEROES TO WS-NUMERIC
.

0160-INITIALIZE-SWITCHES.
SET SW-FIZZ-IS-NOT-TRUE TO TRUE
SET SW-BUZZ-IS-NOT-TRUE TO TRUE
SET SW-NUMERIC-IS-NOT-TRUE TO TRUE
.

0200-CHECK-NUMERIC-FOR-FIZZ.
DIVIDE WS-FIZZBUZZ-ITERATION-COUNTER BY 5 GIVING WS-FIZZ-QUOTIENT REMAINDER WS-FIZZ-REMAINDER.
IF WS-FIZZ-REMAINDER IS EQUAL TO ZERO
SET SW-FIZZ-IS-TRUE TO TRUE.
END-IF
.

0210-WRITE-FIZZ.
IF WS-FIZZ-CHECK = "FIZZ"
MOVE "FIZZ" TO WS-FIZZ
END-IF
.

0300-CHECK-NUMERIC-FOR-BUZZ.
DIVIDE WS-FIZZBUZZ-ITERATION-COUNTER BY 10 GIVING WS-BUZZ-QUOTIENT REMAINDER WS-BUZZ-REMAINDER.
IF WS-FIZZ-REMAINDER IS EQUAL TO ZERO
SET SW-BUZZ-IS-TRUE TO TRUE.
END-IF
.

0310-WRITE-BUZZ.
IF WS-BUZZ-CHECK = "BUZZ"
MOVE "BUZZ" TO WS-BUZZ
END-IF
.

0400-CHECK-NUMERIC-FOR-NUMERIC.
IF NOT WS-FIZZ IS EQUAL TO "FIZZ" AND NOT WS-BUZZ IS EQUAL TO "BUZZ"
SET SW-NUMERIC-IS-TRUE TO TRUE.
END-IF
.

0410-WRITE-NUMERIC.
IF WS-NUMERIC-CHECK = "BUZZ"
MOVE WS-FIZZBUZZ-ITERATION-COUNTER TO WS-NUMERIC
END-IF
.

0500-DISPLAY-RECORD.
IF WS-FIZZ IS EQUAL TO "FIZZ" AND WS-BUZZ IS EQUAL TO "BUZZ"
DISPLAY WS-FIZZBUZZ BEFORE ADVANCING 1 LINE
END-IF
IF WS-FIZZ IS EQUAL TO "FIZZ" AND NOT WS-BUZZ IS EQUAL TO "BUZZ"
DISPLAY WS-FIZZ BEFORE ADVANCING 1 LINE
END-IF
IF NOT WS-FIZZ IS EQUAL TO "FIZZ" AND WS-BUZZ IS EQUAL TO "BUZZ"
DISPLAY WS-BUZZ BEFORE ADVANCING 1 LINE
END-IF
IF NOT WS-FIZZ IS EQUAL TO "FIZZ" AND NOT WS-BUZZ IS EQUAL TO "BUZZ"
DISPLAY WS-NUMERIC BEFORE ADVANCING 1 LINE
END-IF
.
```
Oh, the memory... and the pain...
What language is this?
Aargh... COBOL. I had nearly blocked out my brief, horrifying stint in this language. Thanks. ;)
I'm afraid we are going to have to nuke this post from orbit to be safe!
Ditto what Skliwz said.
Gah! Where's my silver cross and my garlic?!?
You'd need a somewhat recent computer to fit that FizzBuzz program in memory.
As a long time COBOL programmer, I can immediately spot the fact that you are not a natural COBOL programmer. The signs are: All `WORKING-STORAGE` is referenced somewhere in the `PROCEDURE DIVISION`. This is wrong, at least half your `WORKING-STORAGE` should be un-referenced wasted space. Same goes for your paragraphs, there should be a few that are logically unreachable and a few more that have no reference to them. Finally, every COBOL programmer knows you need a paragraph called `MAINLINE`. Excellent work on the logic errors - every COBOL program needs a few of these too. Overall an A+
+6  A:

A short solution, in C:

``````main(i)
{
for(; i < 101; puts(i++ % 5 ? "" : "Buzz"))
printf(i % 3 ? i % 5 ? "%d" : "" : "Fizz", i);
}
``````
this is real nice
+3  A:
``````
WORKING-STORAGE SECTION.

77  FIZZ-NUM  PIC 9(01) VALUE 3.
77  BUZZ-NUM  PIC 9(01) VALUE 5.

01  WS-FLAGS.
05  FIZZ-FLAG         PIC 9(01).
88  PRINT-FIZZ      VALUE 0.
05  BUZZ-FLAG         PIC 9(01).
88  PRINT-BUZZ      VALUE 0.

01  WS-DETAIL-LINE.
05  FILLER            PIC X(02).
05  WS-DETAIL-NUMBER  PIC ZZ9.
05  FILLER            PIC X(03) VALUE ' : '.
05  WS-DETAIL-STRING  PIC X(08).

77  I         PIC 9(03).

PROCEDURE DIVISION.

0000-MAIN.
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 100
MOVE SPACES TO WS-DETAIL-LINE

COMPUTE FIZZ-FLAG = FUNCTION MOD(I, FIZZ-NUM)
COMPUTE BUZZ-FLAG = FUNCTION MOD(I, BUZZ-NUM)

EVALUATE TRUE
WHEN PRINT-FIZZ AND PRINT-BUZZ
MOVE 'FIZZBUZZ' TO  WS-DETAIL-STRING
WHEN PRINT-FIZZ
MOVE 'FIZZ'     TO  WS-DETAIL-STRING
WHEN PRINT-BUZZ
MOVE 'BUZZ'     TO  WS-DETAIL-STRING
WHEN OTHER
MOVE I          TO  WS-DETAIL-STRING
END-EVALUATE

MOVE I TO WS-DETAIL-NUMBER

DISPLAY WS-DETAIL-LINE

END-PERFORM.
``````

I decided to try this in COBOL as a learning exercise and a comparative language study. Wouldn't you know it... it is much longer than my solution in C and took me much longer to write, lookin up the COBOL modulus function (thusfar, financial processing hasn't seen a great need for this) and all that.

I changed the spec a bit to also show me the current value of I, just to make things a bit nicer on me when I looked to make sure it worked. (it does)

+2  A:

This is my version in IA-32 assembly. NASM syntax. Linux only.

(NB: This version is deliberately jump-avoidant. For a more jumpy version, see my next version.)

Edit: Using similar techniques as mentioned in my other version, I've shaved off 21 bytes from the object code, bringing the size to 114 bytes!

``````global  _start

section .text
_start  sub     eax, 104
sub     ebx, 99
lea     esp, [esp + 4*eax]
mov     edi, esp
push    dword 0x7a7a7542        ; Buzz
push    dword 0x7a7a6946        ; Fizz
mov     edx, esp

.loop   lea     ecx, [ebx + 100]
mov     eax, ecx
aam     3
mov     eax, ecx
setz    ch
aam     5
setz    cl
jecxz   .num
and     cl, ch
xor     ch, 1
inc     cl
movzx   esi, ch
movzx   ecx, cl
lea     esi, [edx + 4*esi]
rep movsd
jmp     .nl

.num    lea     eax, [ebx + 100]
aam
xchg    al, ah
test    al, al
setz    cl
push    eax
lea     esi, [edx + ecx - 4]
xor     cl, 1
inc     ecx
rep movsb
pop     eax

.nl     mov     al, 10
stosb
inc     ebx
jle     .loop
lea     eax, [ebx + 3]
sub     edi, edx
lea     ecx, [edx + 8]
lea     edx, [edi - 8]
int     0x80
mov     eax, ebx
dec     ebx
int     0x80
``````

To build, use:

``````nasm -Ox -f elf fizzbuzz.asm
ld -s -m elf_i386 fizzbuzz.o
``````
+2  A:

This is a much more jump-happy version of my last submission. On the upside, the object code size is reduced by 14 bytes, mostly by using `lea` (3 bytes) instead of constant register moves (5 bytes). (e.g., `mov edx, 5` gets translated into `lea edx, [ebx + 4]`, with the understanding that `ebx` is always fixed at 1.)

Edit: Since posting this initially, I've shaved off another 13 bytes, resulting in 108 bytes of object code, by exploiting that most registers start at 0, `edx`'s top bits are never set, and `[edi]` < `[ebp]` < `[esp + 4]` in code size.

Edit2: By buffering all output into the stack before writing, I've shaved off another 8 bytes, resulting in 100 bytes of object code. (Bonus: apart from the Fizz/Buzz pushing, all instructions are 3 bytes or less.) I can cut another 3 bytes by buffering to `.bss` instead of the stack, but using additional sections adds bulk to the executable elsewhere, resulting in a net disadvantage.

``````global  _start

section .text
_start  sub     eax, 104
sub     ebx, 99
push    dword 0x7a7a7542        ; Buzz
push    dword 0x7a7a6946        ; Fizz
mov     esi, esp
lea     esp, [esi + 4*eax]
mov     edi, esp
push    edi

.loop   lea     ecx, [ebx + 100]
mov     eax, ecx
aam     15
jz      .fiftn
mov     eax, ecx
aam     5
jz      .five
mov     eax, ecx
aam     3
jz      .three
mov     eax, ecx
aam
test    ah, ah
jz      .onedig
xchg    ah, al
stosb
xchg    ah, al

.onedig stosb
jmp     .nl

.three  mov     eax, [esi]
stosd
jmp     .nl

.fiftn  mov     eax, [esi]
stosd

.five   mov     eax, [esi + 4]
stosd
jmp     .nl

.nl     mov     al, 10
stosb
inc     ebx
jle     .loop
pop     ecx
mov     edx, edi
sub     edx, ecx
lea     eax, [ebx + 3]
int     0x80
mov     eax, ebx
dec     ebx
int     0x80
``````
+1  A:

ok, my 0.02\$

``````for(int i=0;i<100;i++) printf(((!i%3)+(!i%5))?((!i%3)?"Fizz":"")+((!i%5)?"Buzz":"":i));
``````

It's not pretty and it needs documentation, but it's fun!

+2  A:

In Delphi (complete command-line program):

``````program fizzbuzz;

{\$APPTYPE CONSOLE}

uses
SysUtils;

var
i : integer;

const
c_Start = 1;
c_End = 100;
c_Fizz = 3;
c_Buzz = 5;
c_FizzWord = 'Fizz';
c_BuzzWord = 'Buzz';

begin
for i := c_Start to c_End do begin
if 0=(i mod c_Fizz) then
Write(c_FizzWord);
if 0=(i mod c_Buzz) then
Write(c_BuzzWord);
if (0 < (i mod c_Buzz)) and (0 < (i mod c_Fizz)) then
Write(IntToStr(i));
WriteLn('');
end;  //for
end.
``````
+6  A:

I can think of no reason why you want to, but here's a recursive solution in java:

``````package j;

public class fizzbuzz {

public static void main(String[] args){
System.out.println(fizzBuzz(100));
}

private static String fizzBuzz(int i) {
String val = null;
if(i==0){
return"";
}
else{
val=fizzBuzz(i-1);
}

if(i%15==0){
return val + " FIZZBUZZ";
}else if(i%3==0){
return val+" FIZZ";
}else if(i%5==0){
return val+" BUZZ";
}
else{
return val+" " +String.valueOf(i);
}
}
}
``````

Also, if I do fizzBuzz(5702) I get a java.lang.StackOverflowError. :-)

+1  A:

Use fizzbuzz-maker. You run it and it writes out a file called fizzbuzz.exe, which when run, shows the output required of the original poster.

Because the source code is zero bytes, it wins.

Great, now I have to figure out how to write one of negative size.
+1  A:

D (Digital Mars):

``````#!/usr/bin/dmd -run
/**
* to compile & run:
* \$ dmd -run fizzbuzz.d
* to optimize:
* \$ dmd -O -inline -release fizzbuzz.d
*/
import std.stdio: writeln;
import std.string: toString;

void main() {
for (int i = 1; i <= 100; i++)
writeln(i % 15 == 0 ?  "FizzBuzz" :
i % 3 == 0 ? "Fizz" :
i % 5 == 0 ? "Buzz" : toString(i));
}
``````
+7  A:

When we were interviewing folk for a new position, we used to have candidates walk through this (in the language of their choice, though our shop uses C++) as a bozo filter. I can see that it's now too popular to use this way. ;^)

Occasionally, I'd get someone who claimed to know C++ inside-out, including the libraries. Usually we found some obvious holes. As a lark, I coded up the following FizzBuzz, and asked them to explain how it worked:

``````//////////////////////////////////////////////////////////////////////
//
// Stream obfuscated FizzBuzz example. Ignores most stream failure
// modes and iword/pword callbacks in the interests of
// brevity/obfuscation.

#include <iostream>
#include <string>
#include <ios>
#define IOS std::ios_base
#include <ostream>

using std::cout;
using std::endl;
using std::ostream;
using std::string;

int getIdx()
{
static const int myIdx = IOS::xalloc();
return myIdx;
}

class FizzBuzzer
{
public:
FizzBuzzer() {};
~FizzBuzzer() {};

ostream &print_on(ostream &os) const;
};

ostream &FizzBuzzer::print_on(ostream &os) const
{
const string fizz("Fizz");
const string buzz("Buzz");

long i  = os.iword(getIdx());
void *p = os.pword(getIdx());

if (!p)                                 os << i;
if (reinterpret_cast<long>(p) & 0x02)   os << fizz;
if (reinterpret_cast<long>(p) & 0x01)   os << buzz;

return os;
}

class FizzBuzzManip
{
public:

explicit FizzBuzzManip(int val) : val_d(val) {};

int divisible3() const { return (val_d % 3) ? 0 : 1; }
int divisible5() const { return (val_d % 5) ? 0 : 1; }

private:

int val_d;

friend ostream &operator<<(ostream &os, const FizzBuzzManip &fz)
{
os.iword(getIdx()) = fz.val_d;
os.pword(getIdx()) = reinterpret_cast<void *>( (fz.divisible3() << 1) | fz.divisible5() );

return os;
}
};

ostream &operator<<(ostream &os, const FizzBuzzer &fz)
{
return fz.print_on(os);
}

int main()
{
FizzBuzzer theFizzBuzz;

for (int i = 1; i <= 100; ++i) {
cout << FizzBuzzManip(i) << theFizzBuzz << endl;
}
}
``````
Man, I haven't programmed C++ in a long time and this post doesn't make me want to go back!
Yeah, it *was* a lark!Day to day, if you don't try to be a hero or obscure, C++ still gets my job done without much pain.
Were you trying to be a hero with that code?
No, I was trying to be obscure. This falls into the 'dark corners' thread that pops up now and then on SO. I didn't expect *anyone* to decipher it easily. I just wanted to have a small, bizarre code sample to probe the self-professed 'expert'.
wow, ios::xalloc is truly a dark corner I hope never to need remember, know that i've gone and looked it up to understand this. +1
+1  A:

I'm not very good at golf. Here's `74` characters in Python:

``````for n in range(1,101):print(""if n%3 else"Fizz")+(""if n%5 else"Buzz")or n
``````
+3  A:

C++

``````for(int k=1;k<=100;k++){
if(!(k%3))
cout << "Fizz";
if(!(k%5))
cout << "Buzz";
if((k%3)&&(k%5))
cout << endl << k;
}
``````
+2  A:
+212  A:

You people tend to complicate things a lot, huh?

``````@echo off
echo 1
echo 2
echo Fizz
echo 4
echo Buzz
echo Fizz
echo 7
echo 8
echo Fizz
echo Buzz
echo 11
echo Fizz
echo 13
echo 14
echo FizzBuzz
echo 16
echo 17
echo Fizz
echo 19
echo Buzz
echo Fizz
echo 22
echo 23
echo Fizz
echo Buzz
echo 26
echo Fizz
echo 28
echo 29
echo FizzBuzz
echo 31
echo 32
echo Fizz
echo 34
echo Buzz
echo Fizz
echo 37
echo 38
echo Fizz
echo Buzz
echo 41
echo Fizz
echo 43
echo 44
echo FizzBuzz
echo 46
echo 47
echo Fizz
echo 49
echo Buzz
echo Fizz
echo 52
echo 53
echo Fizz
echo Buzz
echo 56
echo Fizz
echo 58
echo 59
echo FizzBuzz
echo 61
echo 62
echo Fizz
echo 64
echo Buzz
echo Fizz
echo 67
echo 68
echo Fizz
echo Buzz
echo 71
echo Fizz
echo 73
echo 74
echo FizzBuzz
echo 76
echo 77
echo Fizz
echo 79
echo Buzz
echo Fizz
echo 82
echo 83
echo Fizz
echo Buzz
echo 86
echo Fizz
echo 88
echo 89
echo FizzBuzz
echo 91
echo 92
echo Fizz
echo 94
echo Buzz
echo Fizz
echo 97
echo 98
echo Fizz
echo Buzz
``````
That's probably on par with [this answer](#584), but like that answer says, it's not gonna win any golf matches. :-)
So simple and elegant!
you sir, are a genius!
I just think we don't like to type as much ;-)
Of course I cheated, doh!I wrote a small Delphi program that generated this code.
This is how you program if you're paid by the line.
Haven't you heard of loop unrolling?!! duh...
I'd hire you if you wrote this in an interview.
@gabr: I was just going to ask how long the program to generate that code was :).
10 lines, approx
If refactored in C or Assembler it would be the a close to optimum solution for speed/performance on modern hardware!although:main (argc argv) {print "\n1\n2\nFizz\n4\nBuzz ......... \n97\nFizz\nBuzz";return;}Is probably the optimal C solution!
Totally agree. Pfft, loops are for girly men. :)
That's the exact counterpart of Enterprise FizzBuzz - and exactly as sick...
i lol'd :) thanks for this
+1 Roll over [data driven programming](http://www.faqs.org/docs/artu/ch09s01.html)!
+24  A:

Here's the solution in Structured Hebrew (the algorithm language taught in schools in Israel). It's a valid language because I actually wrote a compiler for it once. The following code would actually compile (sans the line numbers, which would be replaced by tabs, which don't work well with right-to-left languages in a left-to-right direction):

``````‫1. הכרז על i: שלם
2. עבור i מ-1 עד 100, בצע:
2.1 אם i % 3 = 0 וגם i % 5 = 0 אזי,
2.1.1 הדפס "FizzBuzz"
2.2 אחרת, אם i % 3 = 0 אזי,
2.2.1 הדפס "Fizz"
2.3 אחרת, אם i % 5 = 0, אזי
2.3.1 הדפס "Buzz"
2.4 אחרת,
2.4.1 הדפס i
``````

SO really needs right-to-left support for this kind of stuff :)

I scanned your line as "It's a valid language because I *accidentally* wrote a compiler for it once." That makes it funny!
+3  A:

The obligatory lisp answer:

``````(loop for x from 1 to 100 do
(format t "~a~%"
(let ((a (cons (= 0 (rem x 3)) (= 0 (rem x 5)))))
(cond
((or (car a) (cdr a))
(format nil "~a~a"
(if (car a) "Foo" "")
(if (cdr a) "Bar" "")))
(T x)))))
``````
+1  A:

Using the new Proc#=== in Ruby 1.9:

``````def divisible_by(factor)
lambda {|product| product.modulo( factor ).zero? }
end

1.upto 100 do |number|
puts case number
when divisible_by 15: "FizzBuzz"
when divisible_by 3: "Fizz"
when divisible_by 5: "Buzz"
else: number
end
end
``````
+31  A:

Anybody can write a oneliner FizzBuzz, but can you generalize it?

Here's a general FizzBuzz function in Haskell:

``````fizzBuzz xs = zipWith (\x y -> if null x then show y else x) (f xs)
where f = foldr (zipWith (++) . mask) (cycle [[]])
mask (k, v) = cycle (replicate (k-1) [] ++ [v])
``````

Here's a sample run:

``````*FizzBuzz> fizzBuzz [(3, "Bucks"), (5, "Fizz"), (7, "Buzz")] [50 .. 150]

["Fizz","Bucks","52","53","Bucks","Fizz","Buzz","Bucks","58","59","BucksFizz","61",
"62","BucksBuzz","64","Fizz","Bucks","67","68","Bucks","FizzBuzz","71","Bucks","73",
"74","BucksFizz","76","Buzz","Bucks","79","Fizz","Bucks","82","83","BucksBuzz",
"Fizz","86","Bucks","88","89","BucksFizz","Buzz","92","Bucks","94","Fizz","Bucks",
"97","Buzz","Bucks","Fizz","101","Bucks","103","104","BucksFizzBuzz","106","107",
"Bucks","109","Fizz","Bucks","Buzz","113","Bucks","Fizz","116","Bucks","118","Buzz",
"BucksFizz","121","122","Bucks","124","Fizz","BucksBuzz","127","128","Bucks","Fizz",
"131","Bucks","Buzz","134","BucksFizz","136","137","Bucks","139","FizzBuzz","Bucks",
"142","143","Bucks","Fizz","146","BucksBuzz","148","149","BucksFizz"]
``````
> but can you generalize it?Ah, a true Haskell programmer...
No true programmer would write a DestroyBaghdad procedure...
+73  A:

Not as weird as some entries but here is a rather unusual python version:

``````a=range(101)
a[0:101:3]=['Fizz']*34
a[0:101:5]=['Buzz']*21
a[0:101:15]=['FizzBuzz']*7
for i in a[1:]: print i
``````
Brilliant. Really, Brilliant.
Yeah. This is nice.
it would be better without hardcoded constants xD
This does not solve the task, because it prints till 101 :P
@Danvil: no it doesn't. range(n) gives numbers from 0 to n-1. And the slice notation works the same way, and doesn't include the end index.
I stand corrected.
Wow. Python without division, modulus, or whitespace. Truly impressive.
+2  A:

Fortran. It has been compiled and run under GNU Fortran, but should work on Fortran 77.

``````*-------------------------------------------------------------------------------
PROGRAM FIZZBUZZ
*
DO 10 I=1,100
A = MOD(I,3)
B = MOD(I,5)
IF (A.EQ.0.AND.B.EQ.0) THEN
PRINT*, 'fizzbuzz'
ELSEIF (A.EQ.0) THEN
PRINT*, 'fizz'
ELSEIF (B.EQ.0) THEN
PRINT*, 'buzz'
ELSE
PRINT*, I
ENDIF
10  END DO
END
``````
+2  A:

Here it is in 6502 code (BBC Basic Assembler):

``````   10 REM FizzBuzz in 6502 assembler
20 DIM code% 1000
30 OSWRCH = &FFEE
40 OSNEWL = &FFE7
50 work = &70
60 DIM FizzM 4 : \$FizzM = "zziF"
70 DIM BuzzM 4 : \$BuzzM = "zzuB"
80 FOR pass% = 0 TO 3 STEP 3
90 P%=code%
100 [opt pass%
110
120 .FizzBuzz  LDA #1
130            LDX #3
140            LDY #5
150 .FB1       SEC
160            DEX
170            BNE FB2
180            JSR Fizz
190            LDX #3
200 .FB2       DEY
210            BNE FB3
220            JSR Buzz
230            LDY #5
240 .FB3       BCC FB4
250            JSR PrDecimal
260 .FB4       PHA
270            JSR OSNEWL
280            PLA
290            CLC
310            CMP #101
320            BCC FB1
330            RTS
340
350 .Fizz      PHA
360            LDX #3
370 .Fizz1     LDA FizzM, X
380            JSR OSWRCH
390            DEX
400            BPL Fizz1
410            CLC
420            PLA
430            RTS
440
450 .Buzz      PHA
460            LDY #3
470 .Buzz1     LDA BuzzM, Y
480            JSR OSWRCH
490            DEY
500            BPL Buzz1
510            CLC
520            PLA
530            RTS
540
550 .PrDecimal STA work
560            PHA
570            TXA
580            PHA
590            LDA #0
600            PHA
610 .PrDec0    LDX #8
620            LDA #0
630 .PrDec1    ASL work
640            ROL A
650            CMP #10
660            BCC PrDec2
670            SBC #10
680            INC work
690 .PrDec2    DEX
700            BNE PrDec1
710            CLC
730            PHA
740            LDX work
750            BNE PrDec0
760 .PrDec3    PLA
770            BEQ PrDec4
780            JSR OSWRCH
790            JMP PrDec3
800 .PrDec4    PLA
810            TAX
820            PLA
830            RTS
840 ]
850 NEXT
``````
+1  A:

There are many ways to write this in Perl 6. This isn't the smallest, but it does show an interesting feature of the language. It can now run in Rakudo Perl 6 right now:

``````multi sub p(Int \$x where {!(\$^n%3 || \$^n%5)}) { "FizzBuzz" };
multi sub p(Int \$x where {!(\$^n%3) && \$^n%5}) { "Fizz" };
multi sub p(Int \$x where {!(\$^n%5) && \$^n%3}) { "Buzz" };
multi sub p(Int \$x) { return \$x; };

for (1..100) -> \$x { say p(\$x) }
``````
+2  A:

Reply to this post here is my generalized version:

``````(defmacro deffoobar (name start end &rest lists)
"Usage: (deffoobar foo 0 200 '(3 . \"Foo\") '(5 . \"Bar\") '(8 . \"Nak\"))"
(let     ((x      (intern (format nil "~a" (gensym))))
(i      (intern (format nil "~a" (gensym))))
(retnum (intern (format nil "~a" (gensym))))
(retval (intern (format nil "~a" (gensym))))
(istart (if (> start end) end start))
(iend   (if (> start end) start end)))
`(defun ,name () ;` //the syntax highlighter is dodgy
(loop for ,x from ,istart to ,iend do
(format t "~a~%"
(let    ((,retnum T)
(,retval ""))
(loop for ,i in (list ,@lists) do
(if (zerop (rem ,x (car ,i)))
(progn
(setf ,retnum nil)
(setf ,retval (format nil "~a~a" ,retval (cdr ,i))))))
(if ,retnum ,x ,retval)))))))
``````
Macros! Love it.
+3  A:

Here's a smaller befunge version. 14x7. I would edit Patrick's, but I don't have enough reputation.

``````1>::3%:   #v_v
v,,:,,"fiz">#<
>\5%:     #v_v
v,,:,,"buz">#<
>\*!    #v_:.v
v5:,*25<   <
v>54**-!#@_1+
``````
+1  A:

Yet another C version (77 chars). People at anarchy golf have managed to bring it down to 73, but as a newbie golfer I can't find any more corners to cut. Ideas?

``````main(i){while(i<101)printf(i%3?i%5?"%d":"":"Fizz",i)|puts(i++%5?"":"Buzz");}
``````
+2  A:

It's the second batch file version, but it's a little more in the spirit of things:

``````@echo off
set i=1
:start

call :test %i%
set /a i=%i%+1
if %i%==101 goto :eof
goto :start

:test
set /a modVal3=%1%%3
set /a modVal5=%1%%5

if %modVal3%%modVal5%==00 (
echo FizzBuzz
) else if %modVal3%==0 (
echo Fizz
) else if %modVal5%==0 (
echo Buzz
) else (
echo %1%
)
``````
+141  A:

Here's a long, yet golfed, perl solution:

``````(                       (
''))=~('('.'?'.'{'.("\`"|
'%').('['^'-').('`'|'!').
('`'|',').'"'.('['^'+').(
((            (
(             ((
(             ((
'['         ))))
)))))^(')')).(
'`'|"\)").(
(              (
'`'))|'.').('['^
'/').'+'.('(').(
'`'^'&').(('`')|
((
((
')'))
))).+(
"\["^

(              (
'!'))).('['^'!')    .')'
.'['.'\\'.('\$').    '_'.
'%'.('^'^(('`')|     ((
(              (
'-')))))).(']').
'.'.'('.('`'^'"'
).('['^'.').('['
^
((
((
'!'))))).(('[')^
'!').')'.('[').
'\\'.'\$'.'_'
.
'%'.('^'^('`'|'+'
)).']'.'|'.'|'.'\\'.
'\$'.'_'.','.'\\'.'\$'
.+             (
((
(
(
(
(
(
'/')))))))).(
(
(
(
'`')))|
'&').('`'|"\/").(
'['^')').('{'^'[').('^'
^('`'|'/'         ))."\.".
((                      '.'

)                         )
.                         (
'^'^('`'|'/')).('^'^(('`')|
'.')).('^'^('`'|'.')).('!'^
(              (          (
(              (          (
(          (
(          (
'+'         )
)))))        )
)
))
).'"'

.              (
'}').')');\$:='.'    ^'~'
;\$~='@'|"\(";\$^=    ')'^
'[';\$/='`'|"\.";     \$,
='('
^+           '}'
;(\$\)         =(
('`'))|        (
(  "\!"));     (
(    \$:))=')'  ^
(       '}');\$~=
(          '*')|
((            ((
'`')
)));
\$^           =((
'+'))         ^+
'_';\$/=        (
(  "\&"))|     (
(    '@'));\$,  =
(       '[')&'~'
;          (\$\)=
((            ((
',')

)))^                   '|';
\$:=('.')^         "\~";\$~=
'@'|'(';\$^=')'^"\[";\$/=
'`'|'.';\$,='('

^'}';\$\
='`'|'!';\$:="\)"^
'}';\$~='*'|'`';\$^="\+"^
('_');\$/=         '&'|'@';
\$,                      =((

(             "\[")))&
((           ('~')));\$\=
((           ','))^    '|'
;           (\$:)=        ((
'.'))^'~';\$~='@'|'(';\$^="\)"^
(          '[');          (
(          \$/))=          (
'`')|'.';\$,='('^'}';\$\=('`')|
((        '!')            )
;\$:=    (')')^           (
('}'));\$~=            (

(
(
(
(
(
(
(
(

(                     ((
'*')                ))  ))
)))             )      )
))|          (      (
'`'       ));\$^=
'+'       ^((
((   ((        '_'
)                  )))
)     )              ;\$/
='&'|                  '@'

;\$,                    =
'['                     &+
((                       ((
(                         (
(                         (
(             ((          (
'~'         ))))))      )))
)));(    (\$\))  =','^"\|";
\$:='.'^"\~";    \$~="\@"|
"\(";\$^=

')'^                   '[';
\$/=('`')|         "\.";\$,=
'('^'}';\$\='`'|"\!";\$:=
')'^'}';\$~='*'

|+
'`';
(\$^)

=('+')^
'_';\$/='&'|'@';\$,
='['&'~';\$\=','^'|';\$:=
'.'^"\~";         \$~="\@"|
((                      '('

)                         )
;                         (
\$^)=')'^'[';\$/='`'|"\.";\$,=
'('^'}';\$\='`'|'!';\$:="\)"^
(              (          (
(              (          (
(              (          (
(              (          (
(             '}'        ))
))           ))))       )))
));(       \$~)= '*'|'`';\$^
='+'^"\_";\$/=   '&'|'@';
\$,='['&'~'      ;\$\=
"\,"^
(
'|');\$:=('.')^
'~';\$~='@'|"\(";
\$^=')'^('[');\$/=
((
((
(
'`')))))|'.';\$,=
'('^'}';\$\="\`"|
'!';\$:=')'^"\}";
(\$~)
=(           '*'
)|'`'         ;(
\$^)='+'        ^
(  '_');\$/     =
(    '&')|'@'  ;
(       \$,)='['&
(          '~');
\$\            =(
',')
^'|'
;(           \$:)
='.'^         ((
"\~"));        (
(  (\$~)))=     (
(    ('@')))|  (
(       '('));\$^
=          "\)"^
((            ((
'[')

)));                   (\$/)
='`'|'.';         \$,="\("^
'}';\$\='`'|'!';\$:="\)"^
'}';\$~='*'|'`'

;\$^='+'
^'_';\$/='&'|"\@";
\$,='['&'~';\$\=','^"\|";
\$:=('.')^         "\~";\$~=
((                      '@'

)             )|'(';\$^
=(           ')')^'[';\$/
=(           "\`")|    '.'
;           (\$,)=        ((
'('))^'}';\$\='`'|'!';\$:="\)"^
(          '}');          (
(          \$~))=          (
'*')|'`';\$^='+'^'_';\$/=('&')|
((        '@')            )
;\$,=    ('[')&           (
('~'));\$\=            (

(
(
(
(
(
(
(
(

(                     ((
',')                ))  ))
)))             )      )
))^          (      (
'|'       ));\$:=
'.'       ^((
((   ((        '~'
)                  )))
)     )              ;\$~
='@'|                  '('

;(           (\$^))=
((             (  (')'))))^
(              ((      '[')
)              );      (\$/)
=              ((      '`')
)|            '.'      ;\$,=
"\("^      '}';\$\      ='`'
|'!';\$:=')'^'}'       ;\$~=
'*'|'`';\$^=         '+'^

'_';                   (\$/)
='&'|'@';         \$,="\["&
'~';\$\=','^'|';\$:="\."^
'~';\$~='@'|'('

;(               (\$^))=
')'^   '[';\$/='`'|('.');\$,=
'('^      '}';\$\='`'|"\!";

\$:               ="\)"^
'}';   \$~='*'|'`';\$^=('+')^
'_';      \$/='&'|('@');\$,=

(             '[')&'~'
;(           \$\)=','^'|'
;(           (\$:))=    '.'
^           "\~";        \$~
='@'|'(';\$^=')'^'[';\$/=('`')|
(          '.');          (
(          \$,))=          (
'(')^'}';\$\='`'|'!';\$:=(')')^
((        '}')            )
;\$~=    ('*')|           (
('`'));\$^=            (

(
(
(
(
(
(
(
(

((
'+')
))))))

)             )))^'_';
\$/           ='&'|'@';\$,
=(           "\[")&    '~'
;           (\$\)=        ((
','))^'|';\$:='.'^'~';\$~="\@"|
(          '(');          (
(          \$^))=          (
')')^'[';\$/='`'|'.';\$,=('(')^
((        '}')            )
;\$\=    ('`')|           (
('!'));\$:=            (

(
')')
)^+
'}'
;\$~
=((
'*'
))|
'`'
;\$^
=
'+'^'_';\$/='&'|"\@";\$,=
'['&'~';\$\=','^'|';\$:='.'^
'~';\$~='@'|'(';\$^=')'^"\[";
(      \$/  )
=     ('`')|
"\.";
(\$,)=
'('^'}';\$\=
'`'|'!';\$:=')'
^+           ((
(              (
(              (
(             ((
'}')       ))))
))));\$~='*'|
"\`";\$^=
(              (
'+'))^'_';\$/='&'
|'@';\$,='['&'~';
\$\=','^('|');\$:=
((
((
'.'))
))^'~'
;(\$~)

=
(                    (
'@'))|'(';\$^=')'^'[';\$/=
'`'|'.';\$,='('^'}';\$\='`'
|
(
((
'!')
));(

\$:
)=((
')')

)
^                    (
'}');\$~='*'|'`';\$^="\+"^
'_';\$/='&'|'@';\$,='['&'~'
;
(
\$\)="\,"^
'|';\$:='.'^'~';\$~=
'@'|'(';\$^=')'^'[';\$/=
"\`"|               "\.";
\$,                       =(
(                         (
(                         (
((                      '('
)))))               ))^((
'}'));\$\='`'|('!');\$:=
')'^'}';\$~="\*"|

('`');\$^=
'+'^'_';\$/='&'|'@'
;\$,='['&'~';\$\=','^'|'
;(\$:)               ='.'^
((                       ((
(                         (
(                         (
((                      '~'
)))))               )))))
;\$~='@'|'(';\$^=')'^'['
;\$/='`'|"\.";#;#
``````

I'm kind of astounded that markdown doesn't have spoiler tags that would have conserved that vertical space...

Wow! Does this actually work too? :O
Yes. Absolutely.
That is the most bizzare code I've ever seen! It looks more like ascii art than anything that works. +1 for sheer coolness.
prime example of obfuscated code
Ascii art code...sounds like time for another StackOverflow question...
Reminds me of the old IOCCC days...
BTW where'd you get an ASCII art generator that lets you supply the exact text without breaking the code?
@Kev: Acme::EyeDrops
You, sir, are my hero.
Wicked cool....
I had a friend who made a lot of entries in the International Obfuscated C Code Contest. This reminds me of his calculation of pi.
IT's been said, but I feel no shame in repeating it. This is really cool.
Took me a second to realise what I was looking at, then I turn my head on its side and voila, pure awesomeness! :D
Any language that allows you to do this should be destroyed, the ashes encased in glass, sealed in concrete, put into a salt mine, pour concrete to fill the salt mine, capping the previous entrance with a solid steel cap, inscribed with pharao-like curses.
@Stafano Borini: thanks
+1  A:

Here's one I did a while ago in Haskell (generalized & should run very quick -- no arithmetic is performed after the initial setup):

``````gizzabuzz pairs combiner = zipWith (\$) (cycle funcs) [1..]
where
funcs = map (\n -> display \$ mapMaybe (filterOut n) sortedPairs) [1..foldr1 lcm \$ map fst \$ sortedPairs]
display [] = show
display xs = foldr1 combiner . sequence (map const xs)
sortedPairs = sortBy (compare `on` fst) pairs
filterOut n (x,y)
| n `mod` x == 0 = Just y
| otherwise      = Nothing

fizzbuzz = gizzabuzz [(3,"Fizz"),(5,"Buzz")] (++)
``````
+37  A:

C# and LINQ? Why not...

``````Enumerable
.Range(1, 100)
.Select(i =>
i % 15 == 0 ? "FizzBuzz" :
i % 5 == 0 ? "Buzz" :
i % 3 == 0 ? "Fizz" :
i.ToString())
.ToList()
.ForEach(Console.WriteLine);
``````
You can further reduce the number of symbols by replacing ForEach(s => Console.WriteLine(s)) with simple ForEach(Console.WriteLine).
That was pretty close to my solution, "1.To(100).ForEach(i => Console.WriteLine(f(i)));" where "f" is a Predicate<int> (Func<int,bool>) with your exact Select logic above, and "To" is an extension method that wraps Enumerable.Range
Also try `Enumerable.Range(1, 100).ToList().ForEach(n => Console.WriteLine((n % 3 == 0) ? (n % 5 == 0) ? "FizzBuzz" : "Fizz" : (n % 5 == 0) ? "Buzz" : n.ToString()));` which is almost identical (except it does away with the .Select) and is 2 characters shorter! ;)
+1  A:

Omg. It seems a challenge :P Readable version, in python :-)

``````for n in xrange(1,101):
s = ''
if n%3 == 0: s += 'Fizz'
if n%5 == 0: s += 'Buzz'
if s == '': s = n
print s
``````
+2  A:
+3  A:
+3  A:

Here's another batch file version (requires Windows 2000 or later).

``````@echo off
setlocal
call :f 1 %%%%i
call :f 3 Fizz
call :f 5 Buzz
call :f 15 FizzBuzz
for /l %%i in (1,1,100) do call echo %%f%%i%%
endlocal
goto :eof
:f
for /l %%i in (%1,%1,100) do set f%%i=%2
goto :eof
``````

I'm truly sorry.

+1  A:

PHP with switch.

I always thought that this switch evaluation rocks, but probably it's just me hating the if's and loving the switch

``````<?php
foreach(range(0,99) as \$number) {
switch(0) {
case \$number % 15:
echo "fizzbuzz";
break;
case \$number % 5:
echo "fizz";
break;
case \$number % 3:
echo "buzz";
break;
default:
echo \$number;
break;
}
echo "\n";
}
?>
``````
+3  A:

C++ version without any runtime conditional branches:

``````#include <iostream>
#include <sstream>

using namespace std;

inline string stringify(int x)
{
ostringstream o;
o << x;
return o.str();
}

template <int N>
struct Enumerator
{
typedef Enumerator<N-1> Prev;
enum {FizzMod = N%3, BuzzMod = N % 5, };

static string FizzBuzz()
{
return Prev::FizzBuzz() + (FizzMod ? string("") : "Fizz") + (BuzzMod ? "" : "Buzz") + ((FizzMod && BuzzMod) ? stringify(N) : "") + "\n";
}
};

template <>
struct Enumerator<0>
{
static string FizzBuzz()
{
return "";
}
};

int main()
{
string fizzBuzz = Enumerator<100>::FizzBuzz();
cout << fizzBuzz;
}
``````
A most wonderful use of templates.Thank you for the entertainment
+1  A:

Ok, here's a recursive solution based on my JavaScript solution. Just another variant...

``````var output = fizzBuzz(1, 100);
function fizzBuzz(i, max){
var fizz = (i % 3 == 0);
var buzz = (i % 5 == 0);
var tmpOutput = "";

if(!fizz && !buzz){
tmpOutput = i;
}else{
if(fizz){
tmpOutput = "Fizz";
}

if(buzz){
tmpOutput += "Buzz";
}
}

tmpOutput += "<br />";

if(i < max){
i++;
tmpOutput += fizzBuzz(i, max);
}

return tmpOutput;
}

document.write(output);
``````
+1  A:

In REBOL:

``````ifmod: func [a n] [either (mod a n) = 0 [n] [0]]
for a 1 100 1 [
print switch (ifmod a 5) + (ifmod a 3) [
8 ["FizzBuzz"]
5 ["Buzz"]
3 ["Fizz"]
0 [a]
]
]
``````
+3  A:

A bit of unrolling and math (Pseudocode):

``````for i = 1..100
switch i % 15
case 0:
print FizzBuzz
break
case 3:
case 6:
case 9:
case 12:
print Fizz
break
case 5:
case 10:
print Buzz
break
default:
print i
break
``````
+3  A:
+1 for variety!
+87  A:

In C:

``````F
``````

Compile with:

``````gcc -DF='main(){int i;for(i=0;i<101;puts(i++%5?"":"Buzz"))printf(i%3?i%5?"%d":"":"Fizz",i);}' fizzbuzz.c
``````
you win ten internets, sir
Can you send them to my home address?
Too good! Haha :)
Looks like the standard *nix hacker solution. Why, can't *nix grow up and realize that you don't need 1000 little apps encapsulating little functions when any average scripting language has 10x as much and handles the logic in a much cleaner manner </rant>
The definition of genius?
I see what you did thar. >_<
+3  A:

Ah what the heck - here's a C# version using list comprehensions:

``````(from i in Enumerable.Range(1, 100)
let fizz = i % 3 == 0 ? "Fizz" : null
let buzz = i % 5 == 0 ? "Buzz" : null
let fizzBuzz = fizz + buzz
select fizzBuzz != string.Empty ? fizzBuzz : i.ToString())
.ToList().ForEach(Console.WriteLine);
``````
+3  A:

57 Chars in MUMPS:

F I=1:1:100 S A=I#3,B=I#5 W:A&B I W:'A "Fizz" W:'B "Buzz"

I feel sorry for you for knowing that
+2  A:

In OCaml:

``````let fb (i:int) : string = match (i mod 3, i mod 5) with
(0,0)->"FizzBuzz"
| (0,_)->"Fizz"
| (_,0)->"Buzz"
|   _  ->string_of_int i
in let rec mklist (n:int):int list =
if n=0 then [] else n::(mklist (n-1))
in (for i=0 to 100 do print_endline (fb i) done;
List.rev_map fb (mklist 100));;
``````

The for loop prints everything out, but isn't purely functional, so I added mklist and the List.rev_map statement which evaluates to a list containing the correct output of the problem. If anyone knows a better way to do this functionally, please let me know.

Pattern matching, I like
+1  A:

Oracle SQL (precondition table with 1 - 100)

``````select decode(mod(id,3),0, decode(mod(id,5),0,'fizzbuzz','fizz'), decode(mod(id,5),0,'buzz,id)) from fizzbuzz
``````
You can do better. Use the Mikito trick (connect by ...) to generate the numbers 1 .. 100 . No need for a fizzbuzz-table.
+3  A:

In R:

``````v <- 1 : 100
fizz <- v %% 3 == 0
buzz <- v %% 5 == 0
rest <- !( fizz | buzz )
s <- paste( ifelse( rest, v, "" ),
ifelse( fizz, "Fizz", "" ),
ifelse( buzz, "Buzz", "" ),
sep="" )
cat( s, sep = '\n' )
``````
+2  A:

T-SQL with no predefined tables. Maybe a little verbose!

``````DECLARE @n AS INT, @m AS INT;
SET @n=1; SET @m=100;
WITH ntom(n) AS(SELECT @n AS n UNION ALL SELECT n+1 FROM ntom WHERE n<@m),
fb AS (SELECT (n%3) AS mod3, (n%5) AS mod5, n FROM ntom)
SELECT CASE WHEN mod3 = 0 AND mod5 = 0 THEN 'FizzBuzz'
WHEN mod3 = 0 THEN 'Fizz' WHEN mod5 = 0 THEN 'Buzz'
ELSE CAST(n AS VARCHAR(10)) END AS fizzbuzz FROM fb;
``````
+3  A:

Here's an XSLT version. The file has a styelsheet reference to itself, so you can open it in IE and see the output:

fb.xml:

``````<?xml version="1.0"?>
<!-- Note: The stylesheet reference to the same file!-->
<?xml-stylesheet href="fb.xml" type="text/xsl" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" >

<xsl:output method="html"/>

<xsl:template match="/">
<xsl:apply-templates select="msxsl:node-set( 1 )/text()"/>
</xsl:template>

<!-- Match all text nodes with values <= 100-->
<xsl:template match="text()[ . &lt;= 100 ]">
<xsl:apply-templates select="." mode="print"/>
<br/>
<!-- Recursion! -->
<xsl:apply-templates select="msxsl:node-set( . + 1 )/text()"/>
</xsl:template>

<xsl:template match="text()" mode="print">
<xsl:value-of select="."/>
</xsl:template>

<xsl:template match="text()[ . mod 3 = 0 ]" mode="print">
Fizz
</xsl:template>

<xsl:template match="text()[ . mod 5 = 0 ]" mode="print">
Buzz
</xsl:template>
<!-- Note: the most specific pattern matches first!-->
<xsl:template match="text()[ . mod 3 = 0 ][ . mod 5 = 0 ]" mode="print">
FizzBuzz
</xsl:template>

<!-- No output for the default node() match-->
<xsl:template match="node()"/>
</xsl:stylesheet>
``````

EDIT: No need for two files (.xml and .xslt).

+2  A:

A short, efficient and easier to read Ruby version.

``````#!/usr/bin/env ruby

1.upto(100) do |i|
print "Fizz" if (i % 3).zero? and (divisible = true)
print "Buzz" if (i % 5).zero? and (divisible = true)
print i if not divisible
print "\n"
end
``````

(divisible = true) is actually an assignment which always returns 'True'. Due to the boolean logic of 'AND', interpreter always evaluates this expression if mod result is 0 (zero), thus resulting an assignment. If mod operation result is non-zero, this expression is never evaluated due to the "boolean shortcut" optimization.

+1  A:

In UniBasic:

``````FOR XX = 1 TO 100
MULT.OF.THREE = NOT(MOD(XX,3))
MULT.OF.FIVE = NOT(MOD(XX,5))
BEGIN CASE
CASE MULT.OF.THREE AND MULT.OF.FIVE
PRINT "FizzBuzz"
CASE MULT.OF.FIVE
PRINT "Buzz"
CASE MULT.OF.THREE
PRINT "Fizz"
CASE 1
PRINT XX
END CASE
NEXT XX
``````
+1  A:

Here is an XSLT version.

``````<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions"&gt;
<xsl:output method="text" version="1.0" encoding="UTF-8" indent="no" />
<xsl:template match="/">
<xsl:for-each select="1 to 100">
<xsl:choose>
<xsl:when test="position() mod 3=0">
fizz
<xsl:if test="position() mod 5=0">
buzz
</xsl:if>
</xsl:when>
<xsl:when test="position() mod 5=0">
buzz
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="position()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
``````

Or much smaller in a function:

``````<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output  method="text"/>
<xsl:template  match="/">
<xsl:value-of  select="for \$n in (1 to 100) return if (\$n mod 3 = 0) then if(\$n mod 5=0) then 'fizzbuzz ' else 'fizz' else if(\$n mod 5=0) then 'buzz' else \$n"/>
</xsl:template>
</xsl:stylesheet>
``````
+1  A:

The shortest I could do with php (70 characters):

``````<?php while(\$i++<100)echo(\$i%15?\$i%3?\$i%5?\$i:Buzz:Fizz:FizzBuzz)."\n";
``````
+2  A:

Oracle SQL

``````select decode(mod(level,3),0, decode(mod(level,5),0,'fizzbuzz','fizz'),
decode(mod(level,5),0,'buzz',level))
from dual
connect by level <= 100
/
``````
+34  A:

Never reinvent the wheel -

``````import urllib, re
fbregexp = re.compile(".*<pre><code>@echo off([0-9a-zA-Z \n]+)</code></pre>", re.DOTALL)
wf = urllib.urlopen("http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem")
wf.close()
if match:
print ''.join(match.group(1).split("echo ")).strip()
else:
print "Unable to fetch fizzbuzz data."
``````
That's awesome xD
Great, "Fizzbuz data" , haha xD
I'm in love with this code!
you frikin' genius!
Blah blah regex blah blah HTML parser blah blah http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
+2  A:

Erlang

``````-module(fizzbuzz).
-export([start/0]).

start() ->
fizzbuzz(1).

fizzbuzz(100) ->
true;
fizzbuzz(X) when (X rem 5 == 0), (X rem 3 == 0) ->
io:format("FizzBuzz~n", []),
fizzbuzz(X+1);
fizzbuzz(X) when X rem 3 == 0 ->
io:format("Fizz~n", []),
fizzbuzz(X+1);
fizzbuzz(X) when X rem 5 == 0 ->
io:format("Buzz~n", []),
fizzbuzz(X+1);
fizzbuzz(X) ->
io:format("~p~n", [X]),
fizzbuzz(X+1).
``````
+2  A:

Not really amazing that the switch version is the fastest...

``````    // 2,6 microseconds
private static void FizzBuzz2()
{
for (int i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
;//Console.WriteLine("FizzBuzz");
else
if (i % 3 == 0)
;//Console.WriteLine("Fizz");
else
if (i % 5 == 0)
;//Console.WriteLine("Buzz");
else
;// Console.WriteLine(i);
}
}

// 1,6 microseconds
private static void FizzBuzz3()
{
for (int i = 0; i <= 100; i++)
{
switch ((i % 3 == 0 ? 0 : 1) + (i % 5 == 0 ? 0 : 2))
{
case 0: ;/*Console.WriteLine("FizzBuzz");*/ break;
case 1: ;/*Console.WriteLine("Fizz");*/ break;
case 2: ;/*Console.WriteLine("Buzz");*/ break;
case 3: ;/*Console.WriteLine(i);*/ break;
}
}
}

// 2,1 microseconds
private static void FizzBuzz4()
{
int i;
for (i = 1; i <= 100; i++)
{
switch (i % 15)
{
case 0: ;/* Console.WriteLine("FizzBuzz");*/ break;
case 3:
case 6:
case 9:
case 12: ;/*Console.WriteLine("Fizz");*/ break;
case 5:
case 10: ;/*Console.WriteLine("Buzz");*/ break;
default: ;/*Console.WriteLine(i);*/ break;
}
}
}

// 11 microseconds
private static void FizzBuzz1()
{
bool b;
string s;
for (int i = 1; i <= 100; i++)
{
b = false;
if (i % 3 == 0)
{
;// Console.Write("Fizz");
b = true;
}
if (i % 5 == 0)
{
;// Console.Write("Buzz");
b = true;
}
s = b ? string.Empty : i.ToString();
;//Console.WriteLine(s);
}
}
``````
+9  A:

C#:

``````    static void Main(string[] args)
{
string[] vals ={"FizzBuzz", "{0}", "{0}", "Fizz", "{0}",
"Buzz", "Fizz", "{0}", "{0}", "Fizz",
"Buzz", "{0}", "Fizz", "{0}", "{0}" };
for (int i = 1; i <= 100; i++)
{
Console.WriteLine(vals[i % 15], i);
}
}
``````
Yuck! :-) ---I need 15 chars
+2  A:

T-SQL

``````WITH Numbers(Number) AS (
SELECT 1
UNION ALL
SELECT Number + 1
FROM Numbers
WHERE Number < 100
)
SELECT
CASE
WHEN Number % 3 = 0 AND Number % 5 = 0 THEN 'FizBuzz'
WHEN Number % 3 = 0 THEN 'Fizz'
WHEN Number % 5 = 0 THEN 'Buzz'
ELSE CONVERT(VARCHAR(3), Number)
END
FROM Numbers
ORDER BY Number
``````
+4  A:

Obfuscated ColdFusion Script Just for the fun of it. Shoot me or any of my developers if we ever did this.

``````function d(n){return chr(inputbasen(n,16));}function f(){writeoutput(d('66')&d('69')&d('7a')&d('7a'));}function b(){writeoutput(d('62')&d('75')&d('7a')&d('7a'));}function r(){writeoutput(d('3c')&d('62')&d('72')&d('3e'));}function m(v){h=v mod 3;n=v mod 9;t=v;if(h AND n){writeoutput(v);r();return;}if(not h)f();if(not n)b();r();}for(x=1;x lte 100;x++){m(x);}
``````

Oh, forgot to say I give this test to all my programmer and DBA applicants. and our requirement is mod 3 and mod 9, with a web output. Thus the output of <br> tags. For you CF haters, yes, it's do-able in much smaller code. :P

+2  A:

My attempt in Java, it seems to work!

``````package Fun;
public class FizzBuzz {
public static void main(String[] args) {
for(int i = 1; i <= 100; i++) {
if((i%3 == 0 || (i%5) == 0)) {
if((i%3) == 0) System.out.print("Fizz");
if((i%5) == 0) System.out.print("Buzz");
}
else { System.out.println(i); }
System.out.println();
}
}
}
``````
A little suggestion to improve both speed and quality of code: Introduce the following flags and substitue usages of the right side value by them. bool canDivideByThree = i%3 == 0; bool canDivideByFive = i%5 == 0;
+3  A:

Factor version. Can probably be made cleaner, clearer and shorter, but I'm still a Factor n00b, so...

``````! Check is a number is divisible by another number
: divisible ( n m -- ? ) mod 0 = ;

! Output a string only if a number is divisible by another and keep the boolean result
: write-if-divisible ( string n m -- ? )
divisible? dup -rot                            ! Is 'n' divisible by 'm'?
[ write ] [ drop ] if ;                        ! If yes print string, otheriwse drop it

! Fizzbuzz procedure
: fizzbuzz ( -- )
100 [                                          ! 100 iterations
1 + dup                                    ! Start at 1 and keep two copies
[ 3 "Fizz" -rot write-if-divisible ]       ! Write "Fizz" if divisible by 3
[ 5 "Buzz" -rot write-if-divisible ] bi or ! Write "Buzz" if divisible by 5
[ "" print drop ] [ . ] if                 ! If divisible by either number print newline otherwise print number
] each ;
``````

Maybe someone can improve this for me?

+2  A:
``````WITH Nbrs(n) AS (
SELECT 1
UNION ALL
SELECT 1 + n FROM Nbrs WHERE n < 100)
SELECT CASE WHEN n%5=0 AND n%3=0 THEN 'BizzBuzz'
WHEN n%3 = 0 THEN 'Bizz'
WHEN n%5 = 0 THEN 'Buzz'
ELSE CAST(n AS VARCHAR(8))
END
FROM Nbrs
OPTION (MAXRECURSION 100);
``````
+2  A:

That's my version in C++, coded in less than 2 minutes and without any test-run before completion. Does that prove I am a good programmer? Certainly not. It just shows that I can solve FizzBuzz in less than 2 minutes. Anyone who can do it in 1 minute (without preliminary thinking, of course)?

This code is exactly the first version I wrote, thus being the first solution that came to my mind. It was not improved or revised afterwards. Maybe "first version contests" could show something about someone's way of thinking.

``````/* first version, not improved or revised */

#include <iostream>

int main() {
bool f;

for (int i = 1; i <= 100; i++) {
f = false;

if (i % 3 == 0) {
std::cout << "Fizz";
f = true;
}
if (i % 5 == 0) {
std::cout << "Buzz";
f = true;
}
if (!f)
std::cout << i;
std::cout << std::endl;
}

return 0;
}
``````
+4  A:

Scala:

``````(1 to 100).foreach(x=>println(if (x%15==0)"FizzBuzz"else if (x%3==0)"Fizz"else if (x%5==0)"Buzz"else x))
``````
+2  A:

Simple, easy answer in python:

``````for x in range(1, 101):
s = ''
if not x % 3:
s = 'Fizz'
if not x % 5:
s += 'Buzz'
print s if len(s) else x
``````
yay for not creating a special case for %15 and having the string 'FizzBuzz' in your code....
+2  A:

PHP, 85 symbols:

``````while(\$i<100){\$i++;echo(\$i%15)?(\$i%3)?(\$i%5)?\$i."\n":"buzz\n":"fizz\n":"fizzbuzz\n";}
``````
+2  A:

In Ocaml.

``````let rec fizzbuzz p =
begin
match p mod 3, p mod 5 with
| 0,0  -> print_string "FizzBuzz"
| 0, _ -> print_string "Fizz"
| _, 0 -> print_string "Buzz"
| _,_ -> print_int p;
end;
print_newline();
if p < 100 then fizzbuzz (p+1);
in fizzbuzz 1;;
``````
+2  A:

C# 3.5 Code generation with CodeDom : 1 statement

``````using System.CodeDom;
public class FizzBuzz
{
static void Main(string[] args)
{
new CSharpCodeProvider().CompileAssemblyFromDom(new System.CodeDom.Compiler.CompilerParameters()
{
GenerateInMemory = true,
}, new CodeCompileUnit()
{
Namespaces = {
new CodeNamespace()
{
Name = "FizzBuzzerNameSpace" ,
Types = {
new CodeTypeDeclaration("FizzBuzzer")
{
Members = {
new CodeMemberMethod()
{
Name="Run",
Attributes = MemberAttributes.Static | MemberAttributes.Public,
Statements = {
new CodeIterationStatement(
new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "i", new CodePrimitiveExpression(0)),
new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(100)),
new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1))),
new CodeConditionStatement(
new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(5)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0))),
new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("FizzBuzz")))
)
{
FalseStatements = {
new CodeConditionStatement(
new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)),
new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("Fizz")))
)
{
FalseStatements = {
new CodeConditionStatement(
new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(5)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)),
new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("Buzz")))
)
{
FalseStatements = {
new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodeVariableReferenceExpression("i"))
}
}
}
}
}
}
)

}
}
}
}
}
}
}
}).CompiledAssembly.GetType("FizzBuzzerNameSpace.FizzBuzzer").GetMethod("Run").Invoke(null, new object[0] { });
}
}
``````

C# 3.5 Code generation with CodeDom multi statement version :

``````using System.CodeDom;
public class FizzBuzz
{
static void Main(string[] args)
{

CodeCompileUnit unit = new CodeCompileUnit();
CodeNamespace ns = new CodeNamespace();
ns.Name = "FizzBuzzerNameSpace";

CodeTypeDeclaration fizzBuzzer = new CodeTypeDeclaration("FizzBuzzer");

CodeMemberMethod run = new CodeMemberMethod();
run.Attributes = MemberAttributes.Static | MemberAttributes.Public;
run.Name = "Run";

CodeIterationStatement forLoop = new CodeIterationStatement();

forLoop.InitStatement = new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "i", new CodePrimitiveExpression(0));
forLoop.IncrementStatement = new CodeAssignStatement(new CodeVariableReferenceExpression("i"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1)));
forLoop.TestExpression = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(100));

CodeBinaryOperatorExpression fizzBuzzCondExpression = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(5)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0)));
var invokeFizzBuzz = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("FizzBuzz")));
CodeConditionStatement fizzBuzzIf = new CodeConditionStatement(fizzBuzzCondExpression, invokeFizzBuzz);

CodeBinaryOperatorExpression fizzCondExpression = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(3)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0));
var invokeFizz = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("Fizz")));
CodeConditionStatement fizzIf = new CodeConditionStatement(fizzCondExpression, invokeFizz);

CodeBinaryOperatorExpression buzzCondExpression = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Modulus, new CodePrimitiveExpression(5)), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(0));
var invokeBuzz = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodePrimitiveExpression("Buzz")));
CodeConditionStatement buzzIf = new CodeConditionStatement(buzzCondExpression, invokeBuzz);
buzzIf.FalseStatements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodeVariableReferenceExpression("i")));

CSharpCodeProvider prov = new CSharpCodeProvider();
var result = prov.CompileAssemblyFromDom(new System.CodeDom.Compiler.CompilerParameters()
{
GenerateInMemory = true,
}, unit);
result.CompiledAssembly.GetType("FizzBuzzerNameSpace.FizzBuzzer").GetMethod("Run").Invoke(null, new object[0] { });
}
}
``````
+3  A:

Didn't see any C++0x + STL solutions, so I decided to ridiculously over-engineer one:

``````#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/math/common_factor.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
using namespace std;
using namespace boost;

namespace {
struct FizzBuzzer {
public:
FizzBuzzer() {
typedef pair<int,string> factor_string_t;
const vector<factor_string_t> factor_pairs
= {make_pair(3,"Fizz"), make_pair(5,"Buzz")};

const unsigned int lcm = accumulate(make_transform_iterator(factor_pairs.begin(),bind(&factor_string_t::first,_1)),
make_transform_iterator(factor_pairs.end(),  bind(&factor_string_t::first,_1)),
1,
lcm_evaluator());

vec_str_.resize(lcm);
for(auto curr; factor_pairs) {
for(int x = 0; x < lcm; x+=curr.first) {
vec_str_[x]+=curr.second;
}
}
}

string operator()(int i) const {
const string& str = vec_str_[i % vec_str_.size()];
if(str.empty())
return lexical_cast<string>(i);
return str;
}
private:
vector<string> vec_str_;
};
}

int main()
{
transform(counting_iterator<int>(0),
counting_iterator<int>(100),
ostream_iterator<string>(cout, "\n"),
FizzBuzzer());
}
``````

Took me ~25 minutes (also had to look up boost's lcm impl, so that is kinda cheating). And I don't have a compiler capable of handling it yet. Probably shouldn't do this in an interview :)

+1 for the sheer line count. I don't care whether it compiles.
+1  A:

Java, 130 characters:

``````public class A{static{for(int i=1;i<100;i++) {boolean b=i%3==0,c=i%5==0;System.out.println(b||c?(b?"Fizz":"")+(c?"Buzz":""):i);}}}
``````

Now, this is kinda cheating, because when you run it at the end it will say:

``````Exception in thread "main" java.lang.NoSuchMethodError: main
``````

But it still works....

+1  A:

Yet Another T-SQL Variation (hadn't seen this one yet):

``````declare @var char(8)
declare @counter int

set @var = 0
set @counter = 0

while @counter < 100
begin
set @counter = @counter +1
set @var = @counter
while @counter % 3 = 0 or @counter % 5 = 0
begin
if @counter % 3 = 0
set @var = 'Fizz'
if @counter % 5 = 0
set @var = 'Buzz'
if @counter % 15 = 0
set @var = 'FizzBuzz'
break
end
print @var
set @var = 0
end
``````
+2  A:

And another T-SQL variation, this one has some close similarities to other posts here. The idea on this one was to avoid using declared variables or any existing data tables.

``````--first we create our temporary test data set using a CTE or Common Table Expression
with testdata (counter) as
(
select 1
union all
select counter +1
from testdata
where (counter + 1) <= 100
)

--next we run against the CTE to generate the FizzBuzz answers

select
case when counter % 3 = 0 or counter % 5 = 0 then
case when counter % 15 = 0 then 'FizzBuzz' else
case when counter % 3 = 0 then 'Fizz' else
case when counter % 5 = 0 then 'Buzz'
end
end
end
else cast(counter as char) end as FizzBuzz
from testdata
``````
+1  A:

Perl:

``````#!/usr/bin/env perl

use strict;
use warnings;

foreach my \$i (1 .. 100)
{
print
!(\$i % 15)
? 'FizzBuzz'
: !(\$i % 5)
? 'Buzz'
: !(\$i % 3)
? 'Fizz'
: \$i;
print "\n";
}
``````

As a one-liner:

``````perl -e 'print \$_%15?\$_%5?\$_%3?\$_:"Fizz":"Buzz":"FizzBuzz","\n"for(1..100)'
``````
The nested conditionals are not very readable.
But the if () {} else {} phrasing is so obvious it isn't worth posting.
+2  A:

Javascript (66 characters):

``````for(var i=1;i<101;i++){alert((i%3?"":"fizz")+(i%5?"":"buzz")||i)};
``````

Warning: Switch alert() to console.log() unless you've got a lot of time to spare

+2  A:

because golf and J are fun:

``````> (((0 = 3 | ]) + 2 * 0 = 5 | ]) { ('Fizz'([ ; ] ; ,)'Buzz') ;~ ":)"0 >: i.100
``````

55 characters with spaces removed, although I'm sure there's room for improvement.

``````(((0 = 3 | ]) + 2 * 0 = 5 | ]) { ('Fizz'([ ; ] ; ,)'Buzz') ;~ ])"0 >: i.100
``````

53 if you don't mind boxed format

+1  A:

Another Java solution, without cheating but with a couple of shorcuts (130 chars):

``````class L{public static void main(String[]a){for(int i=0;i++<100;)System.out.println((i%3>0?"":"fizz")+(i%5>0?i%3>0?i:"":"buzz"));}}
``````

By using the same cheat as Isaac (runs but you get exception), you can get it down to 102 chars:

``````class J{static{for(int i=0;i++<100;)System.out.println((i%3>0?"":"fizz")+(i%5>0?i%3>0?i:"":"buzz"));}}
``````

By really cheating, 68 chars:

``````class C{public static void main(String[]a){System.out.print(a[0]);}}
``````

and passing "1 2 fizz 4 buzz ..." on the command line ;-)

A:

Easiest solution is in python:

```for i in range(1,101):
if not i % 15:
print "FizzBuzz"
elif not i % 3:
print "Fizz"
elif not i % 5:
print "Buzz"
else:
print i

```
Mixing tabs and spaces? Yuck.
could optimize further with a modulo 15
Doesn't print the 100th number.
+7  A:

Of course, in C# you should use a simple linq one liner for something like this

``````string[] fizzBuzz = { "Fizz", "Buzz" };
return String.Join( String.Empty, Enumerable.Range(1, Int32.MaxValue)
.TakeWhile(n => n < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable.Range(1, Int32.MaxValue)
.Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0).Skip(25)
.First()).Select(a => (Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(1).TakeWhile(d => d < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(fizzBuzz.Length + 1).First()).Where(b => a % b == 0)
.Select(c => fizzBuzz[Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(1).TakeWhile(e => e < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(fizzBuzz.Length + 1).First()).IndexOf(c)]).Count() == 0) ? a.ToString() : String
.Join( String.Empty, Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(1).TakeWhile(d => d < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(fizzBuzz.Length + 1).First()).Where(b => a % b == 0)
.Select(c => fizzBuzz[Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(1).TakeWhile(e => e < Enumerable.Range(1, Int32.MaxValue).Where(g => g > 1 && Enumerable
.Range(1, Int32.MaxValue).Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
.Skip(fizzBuzz.Length + 1).First()).IndexOf(c)]).ToArray())).ToArray());
``````

For anyone wondering what it actually does, here is the basic method without inlining of help methods

``````String.Join("",
Utility.PositiveNumbers().TakeWhile(n => n < Utility.Primes().Skip(25).First())
.Select(a => (GetFizzBuzzValues(a).Count() == 0) ? a.ToString() : String.Join("", GetFizzBuzzValues(a).ToArray()))
.ToArray());
``````

where GetFizzBuzzValues works like this

``````public IEnumerable<string>  GetFizzBuzzValues(int a){
return GetFizzBuzzValues(a, FirstXUnEvenPrimes(fizzBuzz.Length));
}

public IEnumerable<string> GetFizzBuzzValues(int a,IEnumerable<int> possible){
return possible.Where(b => a % b == 0).Select(c => fizzBuzz[possible.IndexOf(c)]);
}

public IEnumerable<int> FirstXUnEvenPrimes(int x){
return Utility.Primes().Skip(1).TakeWhile(b => b < Utility.Primes().Skip(x+1 ).First());
}
``````

Finally replace Utility.Primes() and Utility.PositiveNumbers with these two rows.

``````Utility.PositiveNumbers().Where(g => g > 1 && Utility.PositiveNumbers().Skip(1).TakeWhile(i => i < g).Where(h => g % h == 0).Count() == 0)
Enumerable.Range(1, Int32.MaxValue)
``````
+1  A:

TI-BASIC:

``````:For(X,1,100)
:If not(fPart(X/3))
:Disp "FIZZ"
:If not(fPart(X/5))
:Disp "BUZZ"
:If fPart(X/5)≠0 and fPart(x/3)≠0
:Disp X
:End
``````
+2  A:

Clojure. Golfing: 168 chars.

``````(defn \$([n](\$ 1 n))([n t](let[f(=(mod n 3)0)b(=(mod n 5)0)](if(<= n t)(do(if
f(print "Fizz"))(if b(print "Buzz"))(if(not(or f b))(print
n))(newline)(recur(inc n)t))))))
``````

To be called as such: `(\$ n)`

And now legible:

``````(defn fizzbuzz
([n] (fizzbuzz 1 n))
([n top]
(let [fizz (=(mod n 3)0)
buzz (=(mod n 5)0)]
(if (<= n top)
(do
(if fizz
(print "Fizz"))
(if buzz
(print "Buzz"))
(if (not (or fizz buzz))
(print n))
(newline)
(recur (inc n) top))))))
``````

To be called like so: `(fizzbuzz n)`

Could probably be shorter, but I'm still learning the language.

+1  A:

In Perl:

``````use strict;
use warnings;

for my \$num (1 .. 100)
{
my \$str = '';
\$str .= "Fizz" unless \$num % 3;
\$str .= "Buzz" unless \$num % 5;
print \$str || \$num , "\n";
}
``````

This would be a good interview for a Perl job because it can reveal how perlish or Cish the programmer thinks. e.g. I would not be impressed by an intermediate-level programmer writing a C-style solution (`for (\$i = 1; \$i <= 100; \$i++)`, if-blocks with indentation (i.e. `if (blah) { stuff }` rather than `stuff if blah`), etc).

+2  A:

Here is a one liner in Lua (88 characters):

``````for i=1,100 do print(i%15==0 and"FizzBuzz"or i%3==0 and"Fizz"or i%5==0 and"Buzz"or i)end
``````

(EDIT) And here is the generalized version:

``````function f(t) for i=t.s,t.e do r="" for _,v in ipairs(t) do r=r..(i%v[1]==0 and v[2] or "") end print(#r==0 and i or r) end end
f{s=1,e=100,{3,"Fizz"},{5,"Buzz"}}
``````
+9  A:

Note: this is just for my C practice. I am just thrilled it even works :)

``````main()
{
int i;

for (i = 1; i <= 100; i++)

{

if  (
(i % 3 == 0) && (!(i % 5 == 0))
)
{ printf ("Fizz\n");
continue;
}

else if (
(i % 3 != 0) && (i % 5 == 0 )
)
{ printf ("Buzz\n");
continue;
}

else if (
(i % 3 == 0) && (i % 5 == 0)
)
{ printf ("FizzBuzz\n");
continue;
}
else if  (
(!(i % 3 ==0)) && (!(i % 5 == 0))
)
{ printf ("%d\n", i);
continue;
}

}
system("PAUSE");
return 0;

}
``````
Since you have the nested if-then-else I think you don't need the last arithmetic test...I will be looking forward to your next code-golf...
You don't have to use "continue;" you can remove all of them on this program. note that some systems may not have "PAUSE", such as my Linux system.
YOU GO LAURA! Keep it up :)
Thanks! +1 for being such an encouragement!
Every time you write system("PAUSE") in your C code, God kills a very cute animal. Use getch() instead (it is not a system call, and works everywhere).
+1  A:

In PHP using the under appreciated ternary operator ?: You either love it or hate it.

``````<?php

foreach (range(1,100) as \$i)
echo \$i % 3 == 0 ? ( \$i % 5 == 0 ? "FizzBuzz\n" : "Fizz\n" ) : ( \$i % 5 == 0 ? "Buzz\n" : \$i."\n" );

?>
``````
+2  A:

In Common Lisp a straightforward iterative solution would be:

``````(loop for i from 1 to 100 do
(cond ((zerop (mod i 15)) (format t "FizzBuzz "))
((zerop (mod i 3)) (format t "Fizz "))
((zerop (mod i 5)) (format t "Buzz "))
(t (format t "~A " i))))
``````

But it's common to think of a recursive solution when programming in Common Lisp, and so an easy one - although not very efficient - would be:

``````(defun fizzbuzz (i)
(unless (zerop i)
(append (fizzbuzz (1- i))
(list (cond ((zerop (mod i 15)) 'FizzBuzz)
((zerop (mod i 3)) 'Fizz)
((zerop (mod i 5)) 'Buzz)
(t i))))))

(fizzbuzz 100)
``````

That version could easily blow the stack, a better version would be a tail recursive one, which carries the result through the recursive calls:

``````(defun fizzbuzz-tail-recursive (i)
(fb-recursive i '()))

(defun fb-recursive (x result)
(if (zerop x)
result
(fb-recursive (1- x)
(cons (cond ((zerop (mod x 15)) 'FizzBuzz)
((zerop (mod x 3)) 'Fizz)
((zerop (mod x 5)) 'Buzz)
(t x))
result))))

(fizzbuzz-tail-recursive 100)
``````

Which is also way a lot faster than the non-tail-recursive version.

``````[25]> (time (progn (fizzbuzz 7000) nil))
Real time: 3.255142 sec.
Run time: 3.146522 sec.
Space: 196028000 Bytes
GC: 361, GC time: 1.831725 sec.
NIL
[26]> (time (progn (fizzbuzz-tail-recursive 7000) nil))
Real time: 0.003486 sec.
Run time: 0.002999 sec.
Space: 56000 Bytes
NIL
``````

And with a call to `fizzbuzz` with 1 million:

``````[52]> (time (progn (fizzbuzz 1000000) nil))

*** - Program stack overflow. RESET
Real time: 0.010824 sec.
Run time: 0.010998 sec.
Space: 0 Bytes

[53]> (time (progn (fizzbuzz-tail-recursive 1000000) nil))
Real time: 1.200375 sec.
Run time: 1.095833 sec.
Space: 8000000 Bytes
GC: 8, GC time: 0.230964 sec.
NIL
``````
+1  A:

One of many possible answers in J:

``````fb=: 3 : '(#. 0 = 3 5|y) { (": y); ''buzz'' ; ''fizz''; ''fizzbuzz'''
fb"0 1+i.100
``````

This one is nice because it's actually readable (and not hardcoded to 100).

More criptic:

``````fb2 =: 3 : '(<"1 (i. y),.{:&bx"1 [ 0 = 1 3 5 15 |"_ 0 [1+i.y) { (,.":&.>1+i.y),"1 ''fizz'';''buzz'';''fizzbuzz'''
fb2 100
``````

I'm too lazy at the moment to code a version that concatenates 'fizz' and 'buzz' for multiples of 15...

+1  A:

Best golf I could do in PHP (81 chars):

``````for(\$a=0;\$a<101;\$a++){
\$b=(!\$a%3)?\$b='fizz':'';
if(!\$a%5)\$b.='buzz';
echo \$b?\$b:\$a;}
``````
+2  A:

Surely all that division has to be a massive performance bottleneck!

Much better to use multiplication to work out the fizz and buzz in advance.

``````int next_fizz = 3;
int next_buzz = 5;
for (int i = 1; i <= 100; i++)
{
if (i != next_fizz && i != next_buzz)
{
printf("%d\r\n", i);
}
else
{
if (i == next_fizz)
{
printf("fizz");
next_fizz += 3;
}
if (i == next_buzz)
{
printf("buzz");
next_buzz += 5;
}
printf("\r\n");
}
}
``````
+2  A:

Ok, here is a C# lambda extensible fizzbuzz! I was actually asked this in an interview today and I provided a crappy solution. So now here is a good one.

``````    public static void FizzBuzz()
{
Dictionary<Func<int, bool>, Func<int, string>> rules = new Dictionary<Func<int, bool>, Func<int, string>>();
rules.Add(x => x % 3 == 0, x => "fizz");
rules.Add(x => x % 5 == 0, x => "buzz");
rules.Add(x => x % 5 != 0 && x % 3 != 0, x => x.ToString());
rules.Add(x => true, x => "\n");

var output = from n in Enumerable.Range(1, 100)
from f in rules
where f.Key(n)
select f.Value(n);

output.ToList().ForEach(x => Console.Write(x));
}
``````
+1  A:

Ruby using Enumerable#collect.

``````(1..100).collect { |x| x%15==0 ? "fizzbuzz" : x%3==0 ? "fizz" : x%5==0 ? "buzz" : x }
``````
+1  A:

a basic action script version

``````fizzBuzz(100);
function fizzBuzz(i:int) {
var a:int=0;
while (a<i) {
a++;
if ( a%3 == 0 && a%5 == 0 ) {
trace("fizzBuzz");
} else if ( a%3 == 0 ) {
trace("fizz");
} else if ( a%5 == 0 ) {
trace("buzz ");
} else {
trace(a);
}
}
}
``````
+1  A:

Another C version (139 chars)

``````#include <stdio.h>
int main(){int i=0;while(++i<101){((i%3==0?printf("Fizz"):0)|(i%5==0?printf("Buzz"):0))==0?printf("%d", i):0;puts("");}}
``````

``````#include <stdio.h>
int main()
{
int i = 0;
while(++i < 101)
{
((i % 3 == 0 ? printf("Fizz") : 0) | (i % 5 == 0 ? printf("Buzz") : 0)) == 0 ? printf("%d", i) : 0; puts("");
}
}
``````

Lesson learned is this: Never search for "What is the definition of enterprise software?" on SO as it inevitably leads you to Enterprise FizzBuzz.

Unfortunately if you are reading this warning, it's already too late.

+1  A:

My little javascript solution:

``````(function(i){if(i){arguments.callee(--i); console.log(i%15 ? (i%3 ? (i%5 ? i : 'Buzz') : 'Fizz') : 'FizzBuzz')}})(101);
``````

Notice that it requires the firebug console or something else. I feel the code that goes as console.log parameter must be improved!

+1  A:

This is rather late to the party, but here is my python version in 100 characters:

``````print '\n'.join((("Fizz" if (x%3==0)else"")+("Buzz"if(x%5==0)else"")or str(x)for x in xrange(100)))
``````
+1  A:

Written in jass, 1738 characters. Jass is the language which is used in order to create Warcraft 3 modules.

``````    function Trig_fizzbuzz_Copy_Func001Func001Func002Func002C takes nothing returns boolean
if ( not ( ModuloInteger(GetForLoopIndexA(), 3) == 0 ) ) then
return false
endif
return true
endfunction

function Trig_fizzbuzz_Copy_Func001Func001Func002C takes nothing returns boolean
if ( not ( ModuloInteger(GetForLoopIndexA(), 5) == 0 ) ) then
return false
endif
return true
endfunction

function Trig_fizzbuzz_Copy_Func001Func001C takes nothing returns boolean
if ( not ( ModuloInteger(GetForLoopIndexA(), 15) == 0 ) ) then
return false
endif
return true
endfunction

function Trig_fizzbuzz_Copy_Actions takes nothing returns nothing
set bj_forLoopAIndex = 1
set bj_forLoopAIndexEnd = 100
loop
exitwhen bj_forLoopAIndex > bj_forLoopAIndexEnd
if ( Trig_fizzbuzz_Copy_Func001Func001C() ) then
call DisplayTextToForce( GetPlayersAll(), "TRIGSTR_017" )
else
if ( Trig_fizzbuzz_Copy_Func001Func001Func002C() ) then
call DisplayTextToForce( GetPlayersAll(), "TRIGSTR_016" )
else
if ( Trig_fizzbuzz_Copy_Func001Func001Func002Func002C() ) then
call DisplayTextToForce( GetPlayersAll(), "TRIGSTR_015" )
else
call DisplayTextToForce( GetPlayersAll(), I2S(GetForLoopIndexA()) )
endif
endif
endif
call TriggerSleepAction( 0.10 )
set bj_forLoopAIndex = bj_forLoopAIndex + 1
endloop
call CustomDefeatBJ( Player(0), "TRIGSTR_018" )
endfunction

//===========================================================================
function InitTrig_fizzbuzz_raw takes nothing returns nothing
set gg_trg_fizzbuzz_raw = CreateTrigger(  )
call TriggerRegisterTimerEventSingle( gg_trg_fizzbuzz_raw, 1.00 )
call TriggerAddAction( gg_trg_fizzbuzz_raw, function Trig_fizzbuzz_Copy_Actions )
endfunction
``````
+1  A:

A little bit late =P but here is my answer

EDIT: made it shorter - 99 chars

C#

``````for(int i=1;i<=100;i++){Console.Write(i%3==0?i%5==0?"FizzBuzz":"Fizz":i%5==0?"Buzz":i.ToString());}
``````
+2  A:

Mathematica: (85 characters)

``````Scan[Print@Switch[Mod[#,15],0,"FizzBuzz",3|6|9|12,"Fizz",5|10,"Buzz",_,#]&,Range@100]
``````
+2  A:

Perl, using regular expressions rather than aritmetic:

``````\$output = join(" ",1 .. 100);
\$output =~ s/((\S+ ){2})\S+/\$1Fizz/g;
\$output =~ s/((\S+ ){4})\S+/\$1Buzz/g;
\$output =~ s/((\S+ ){14})\S+/\$1FizzBuzz/g;
print \$output;
``````
A:

for x in range(1,100): r1 = x % 3 r2 = x % 5 if not r1: print 'Fizz' if not r2: print 'Buzz' if not r1 and not r2: 'FizzBuzz'

duplicate of: http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/2429947#2429947
A:
``````for x in range(1,100):
r1 = x % 3
r2 = x % 5
if not r1: print 'Fizz'
if not r2: print 'Buzz'
if not r1 and not r2: print 'FizzBuzz'
``````
This is not correct. For example for `x == 15` it prints "Fizz", "Buzz" **and** "FizzBuzz".
Also stores two unnecessary booleans.
and the loop is not began and finished i mean where are {}
@Behrooz: Looks like Python
+1  A:

Easy.. PHP as such:

\$i=1;while(\$i<=100){if(!(\$i%15)){\$output='fizzbuzz';}elseif(!(\$i%5)){\$output='buzz';}elseif(!(\$i%3)){\$output='fizz';}else{\$output=\$i;}print(\$output);echo "\n";\$i++;}

Or does it need to be more readable?

``````\$i = 1;
while (\$i <= 100) {
if (!(\$i % 15)) {
\$output = 'fizzbuzz';
} elseif (!(\$i % 5)) {
\$output = 'buzz';
} elseif (!(\$i % 3)) {
\$output = 'fizz';
} else {
\$output = \$i;
}
print (\$output);
echo "\n";
\$i++;
}
``````
+1  A:

C# (114 characters, without spaces):

``````Enumerable.Range(1, 100).Select(a => a%15==0 ? "FizzBuzz" : a%3==0 ? "Fizz" : a%5==0? "Buzz" : a.ToString()).Run(Console.Write);
``````
+1  A:

Mine one in C# using For Loop also we can use foreach one also

``````var i = 1;
for (i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Response.Write("FizzBuzz \n");
}
else if (i % 3 == 0)
{
Response.Write("Fizz \n");
}
else if (i % 5 == 0)
{
Response.Write("Buzz \n");
}
else
{
Response.Write(i);
}

}
``````
+1  A:
``````foreach(range(1, 100) as \$n) {
if(is_int(\$n/3) && is_int(\$n/5)) { print 'FizzBuzz<br/>'; }
elseif(is_int(\$n/3)) { print 'Fizz<br/>'; }
elseif(is_int(\$n/5)) { print 'Buzz<br/>'; }
else { print \$n.'<br/>'; }
}
``````

My PHP version, using is_int() to tell if it evenly divides and using range() to make an array of numbers from 1 to 100 pretty quickly.

Edit: Condensed.

``````<?php foreach(range(1, 100) as \$n) { if(is_int(\$n/3) && is_int(\$n/5)) { print 'FizzBuzz'; } elseif(is_int(\$n/3)) { print 'Fizz'; } elseif(is_int(\$n/5)) { print 'Buzz'; } else { print \$n.''; } } ?>
``````
+1  A:

Nobody wrote a dc entry!!!

Here it is... (65 chars for golf)

``````[[Fizz]P]sF[[Buzz]P]sB[dn]sN100[dd3%d0=Fr5%d0=B*0!=NAP1-d0<L]dsLx
``````
+1  A:

how about some ANSI C..

``````int state;
for(int i = 1; i <=100;i++)
{
state = ((i%3) == 0) + (((i%5) == 0) <<1);
if((state & 1) == 1)printf("Fizz");
if((state & 2) == 2)printf("Bang");
if(state == 0) printf("%i",i);
}
``````

or even shorter:

``````char *c[] = {"%i \0","Fizz \0", "Buzz \0", "FizzBuzz \0"};
for(int i = 0; i < 100; printf(c[((i%3)==0)+(((i%5)==0)<<1)], i))i++;
``````
A:

My C# version

for(int i=1; i<101; i++) Console.WriteLine (i%3 == 0 && i%5 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz": i % 5 == 0 ? "Buzz" : i.ToString());

+1  A:

C#

``````Console.WriteLine(string.Join(", ", Enumerable.Range(1, 100).Select<int, string>(
(number) => number % 15 == 0 ? "Fizz Buzz" : number % 3 == 0
? "Fizz" : number % 5 == 0 ? "Buzz" : number.ToString()).ToArray()));
``````
+2  A:

Scala:

``````object FizzBuzz {
def main(args: Array[String]): Unit = {
for(i <- 1 to 100) {
println(
(i % 3, i % 5) match {
case(0, 0) => "FizzBuzz"
case(0, _) => "Fizz"
case(_, 0) => "Buzz"
case _     => i
}
)
}
}
}
``````
+2  A:

My favorite ...

``````for i = 1 to 100
select case i
case 1
debug.print i
case 2
debug.print i
case 3
debug.print "fizz"
case 4
debug.print i
case 5
debug.print "buzz"
case 6
debug.print "fizz"
case 7
debug.print i
case 8
debug.print i
case 9
debug.print "fizz"
case 10
debug.print "buzz"
case 11
debug.print i
case 12
debug.print "fizz"
case 13
debug.print i
case 14
debug.print i
case 15
debug.print "fizzbuzz"
...
...
end select
next i
``````
+52  A:

# HTML/CSS

``````<!DOCTYPE html>
<html>
<title>CSS FizzBuzz</title>
<style type="text/css">
body {counter-reset:fb;}
div:before {content:counter(fb);counter-increment:fb;}
div:nth-child(3n+0):before {content:'Fizz';}
div:nth-child(5n+0):before {content:'Buzz';}
div:nth-child(15n+0):before {content:'FizzBuzz';}
</style>
<body>
<div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div>
</body>
</html>
``````
That's one cool idea! +1
To make it completely semantic, it's possible that it should be a list with `<ul>` and `<li>` instead of divs, but it's the css that counts. :P
Awesome. +1 for such a crazy idea!
there you go.. made it semantic too :) http://jsfiddle.net/DXyQ6/
Use an OL and you won't need the counter and counter reset.
@Kent - you try that and find out why that doesn't work.
+2  A:

C# 4 version. I particularly like this because it is so easy to add new rules (e.g. modulo 7 = "Bang")

``````void FizzBuzz()
{
var rules = new[]
{
new { Name = "Fizz", Modulus = 3 },
new { Name = "Buzz", Modulus = 5 },
};

Enumerable.Range(1, 100).Select(i => i.ToString()).Zip
(
rules.Select(r => CreateSequence(r.Modulus, r.Name))
.Aggregate((f, b) => f.Zip(b, (x, y) => x + y)),
(i, s) => String.IsNullOrEmpty(s) ? i : s
)
.ToList().ForEach(Console.WriteLine);
}

private static IEnumerable<string> CreateSequence(int modulus, string name)
{
while (true)
{
for (int i = 1; i < modulus; ++i)
yield return null;
yield return name;
}
}
``````
+6  A:

A LOLCODE implementation I made for practicing the language, I plan on using it on the qualification round of Google CodeJam:

``````#!/usr/local/bin/lolcode -f

HAI
CAN HAS STDIO?

IM IN YR LOOP UPPIN YR N WILE DIFFRINT N AN 101
BOTH SAEM N AN 0, O RLY? YA RLY, N R 1, OIC

BOTH SAEM MOD OF N AN 3 AN 0, O RLY?, YA RLY, VISIBLE "FIZZ"!, OIC
BOTH SAEM MOD OF N AN 5 AN 0, O RLY?, YA RLY, VISIBLE "BUZZ"!, OIC

BOTH OF DIFFRINT MOD OF N AN 3 AN 0 AN DIFFRINT MOD OF N AN 5 AN 0
O RLY?
YA RLY, VISIBLE N!
OIC

VISIBLE ""
IM OUTTA YR LOOP
KTHXBYE
``````
+1  A:

## FizzBuzz in 56 characters of J.

``````   ((0 i.~15 3 5|]){::'FizzBuzz';'Fizz';'Buzz';":)"0>:i.100
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
``````
This is just what I was looking for! Thanks!
+2  A:

## Groovy One-Liner

Can be run in a browser via the Groovy web console

``````1.upto 100, {println !(it % 15) ? "fizzbuzz" : !(it % 3) ? "fizz" : !(it % 5) ? "buzz" : it}
``````

A more readable version is:

``````1.upto 100, {

def fizz = it % 3 == 0
def buzz = it % 5 == 0

println fizz && buzz ? "fizzbuzz" : fizz ? "fizz" : buzz ? "buzz" : it
}
``````
Bonus points for using ?:
+1  A:

I know that there was already answer with erlang implementation, but it was only sequential usage of erlang. But having erlang let's actually spawn some processes! And as a bonus another version of sequential approach using map instead of recursion.

``````-module(fizzbuzz).
-compile(export_all).

fizzbuzz(N) when N rem 15 == 0 ->
"fizzbuzz";
fizzbuzz(N) when N rem 3 == 0 ->
"fizz";
fizzbuzz(N) when N rem 5 == 0 ->
"buzz";
fizzbuzz(N) ->
N.

pmap(F, L) ->
Parent = self(),
[receive {Pid, Result} -> Result end
|| Pid <-
[spawn(fun() -> Parent ! {self(), F(X)} end) || X <- L]].

% make decisions in parallel
par(N) when N >= 1 ->
lists:foldl(
fun(X,_) -> io:format("~p~n",[X]) end, [],
pmap(fun fizzbuzz/1, lists:seq(1,N)));

% make decisions sequentially
seq(N) when N >= 1 ->
lists:foldl(
fun(X,_) -> io:format("~p~n",[X]) end, [],
lists:map(fun fizzbuzz/1, lists:seq(1,N)));
``````
+1  A:

Quickie C# (141 139 chars):

``````public static void O(int i){Console.WriteLine((i%3==0&&i%5==0)?"FizzBuzz":(i%3==0)?"Fizz":(i%5==0)?"Buzz":i.ToString());if(i<100){O(i+1);}}
``````
+2  A:

Some simple python, generalized. Opinions are welcome.

• a = start of range
• b = end of range
• c = any number of arguments (separated by commas) in this fashion: 'saywhat'=29

in our simple case you call q(1,100,'fizz'=3,'buzz'=5)

``````def q(a, b, **c):
for i in range(a, b+1):
d = ''
for j in c:
if i % c[j] < 1: d += j
print d or i
``````
cute and clever
thank you so much for your revision. I havent been toying a lot with programming since I posted this and it was a real pleasure to find out the "print d or i" thing :-)
+2  A:

A JavaScript one-liner (60 characters):

``````for(i=1;i<101;i++)alert((i%3?"":"Fizz")+(i%5?"":"Buzz")||i)​
``````

Explanation:

``````for(i=1;i<101;i++)  // Loop for i=1 to i=100
alert(              // Output to the user
(i%3)?"":"Fizz")+   // If i%3!=0 then "" otherwise "Fizz"
(i%5)?"":"Buzz")    // If i%5!=0 then "" otherwise "Buzz"
||i)                // If left side is falsy return i
``````

Note: An empty string in Javascript is treated as false when used as a boolean.

And another one using an Array to loop:

``````for(i in new Array(100).join(0).split(0))alert(((++i)%3?"":"Fizz")+(i%5?"":"Buzz")||i)​
``````
+1  A:

A Ruby solution that uses neither division nor modulus:

``````puts (1..100).map{|i|
o=""
o<<"Fizz" if ('o' * i) =~ /^\$|^(...)\1*\$/
o<<"Buzz" if ('o' * i) =~ /^\$|^(.....)\1*\$/
o=i.to_s if o.empty?
o
}
``````
+2  A:

Compressed Python weighing in at 228 bytes, which is more than half as small as Grant’s:

``````print '''
eJxNzbsNxDAMA9Ce2+hjfdoU2eUGuCbT52ALOFamKRBPoLg/zwPH9f09OyfqhF2JnI8YxHc8dUBy
Lk1jVajRXGP6gvZ/bgIb2ti2hLHuo7vBSfeAj+6sL8VifY2+Cov0EMTowXokgvUcPQ1JegZy9GS9
FMV6jV6FIr0FPXqz3ok++gufUm5s'''.decode('base64').decode('zlib')
``````
+1  A:

Good ol' C, nothing beats that! Here's a version with no mods or divides...

``````#include <stdio.h>

int
main()
{
int three_count = 0;
int five_count = 0;
int val;

for (val = 1; val <= 100; val++)
{
three_count++;
five_count++;

if (three_count != 3 && five_count != 5)
{
printf("%d", val);
}
else
{
if (three_count == 3)
{
printf("Fizz");
three_count = 0;
}
if (five_count == 5)
{
printf("Buzz");
five_count = 0;
}
}

printf("\n");
}

return 0;
}
``````

Here's another solution...

``````/*
* Better than my previous attempt? You decide.
*/

#include <stdio.h>

int
main()
{
int fifteen_count = 0;
int val;

for (val = 1; val <= 100; val++)
{
fifteen_count++;

switch (fifteen_count)
{
case 3:
case 6:
case 9:
case 12:
printf("Fizz\n");
break;
case 5:
case 10:
printf("Buzz\n");
break;
case 15:
printf("FizzBuzz\n");
fifteen_count = 0;
break;
default:
printf("%d\n", val);
break;
}
}

return 0;
}
``````
I could eliminate one integer local variable if I counted to 15 instead, and then tested for equality with 3, 5, 6, 9, 10, 12 and 15 before resetting the counter to 0. But the code would be longer too.
+1  A:

Now that I have attempted this, I see there is a balance between redundancy and simplicity, where there is no pretty solution to. Bummer

Here is my best in PHP:

``````for(\$i=1; \$i<=100; \$i++){
if (\$i%3) echo 'Fizz';
if (\$i%5) echo 'Buzz';
if (!\$i%3 && !\$i%5) echo \$i; //I know I could optimize with %15, but that would be less clear
}
``````
No, you can't optimize with %15
Also Fizzbuzz should be on the same line
+2  A:

No template abuse?

``````template<int I, bool mod3 = (I % 3) == 0, bool mod5 = (I % 5) == 0> struct FizzBuzz {
static const std::string lolcakes = std::string(1, I + '0') + "\n" + FizzBuzz<I + 1>::lolcakes;
};
template<bool mod3, bool mod5> struct FizzBuzz<100, mod3, mod5> {
static const std::string lolcakes = "";
};
template<int I, bool mod5> struct FizzBuzz<I, true, mod5> {
static const std::string lolcakes = "Fizz\n" + FizzBuzz<I + 1>::lolcakes;
};
template<int I, bool mod3> struct FizzBuzz<I, mod3, true> {
static const std::string lolcakes = "Buzz\n" + FizzBuzz<I + 1>::lolcakes;
};
template<int I> struct FizzBuzz<I, true, true> {
static const std::string lolcakes = "FizzBuzz\n" + FizzBuzz<I + 1>::lolcakes;
};
std::cout << FizzBuzz<0>::lolcakes;
``````

On reflection, this probably won't compute FizzBuzz at compile time. But it would do if C++ could mutate strings at compile-time in a defined fashion.

+1  A:

In Haskell, as clear as I could get it:

``````import Data.List

fizzbuzz :: Integer -> String
fizzbuzz x
| x `mod` 15 == 0   = "fizzbuzz"
| x `mod` 5 == 0    = "buzz"
| x `mod` 3 == 0    = "fizz"
| otherwise = show x

fizzbuzz100 = intercalate " " . map fizzbuzz \$ [1..100]
``````

That was my first Haskell program. :)

In C, done as a tangly mess, as a rant against tangly messes:

``````#include <stdio.h>

main(){
int i;
for (i=1;i<90;i+=15) {
printf("%d %d fizz %d buzz fizz %d %d fizz buzz %d fizz %d %d fizzbuzz ",
i, i+1, i+3, i+6, i+7, i+10, i+12, i+13);
}
printf("%d %d fizz %d buzz fizz %d %d fizz buzz\n", i, i+1, i+3, i+6, i+7);
}
``````

In fortran, just for fun:

``````c  FORTRAN fizzbuzz

program main
implicit none
integer i
logical i3
logical i5
do i = 1, 100
i3 = .false.
i5 = .false.
if ( i / 5 * 5 .eq. i ) then
i3 = .true.
end if
if ( i / 3 * 3 .eq. i ) then
i5 = .true.
end if
if ( i5 .and. i3 ) then
write ( *, '(a)' ) 'fizzbuzz'
end if
if ( i5 ) then
write ( *, '(a)' ) 'buzz'
end if
if ( i3 ) then
write ( *, '(a)' ) 'fizz'
end if
if ( .not. i3 .and. .not. i5 ) then
write ( *, '(i2)') i
end if
end do
stop
end
``````

In fortran of an older style:

``````C FIZZBUZZ

PROGRAM MAIN
101   FORMAT (A)
102   FORMAT (I2)

INTEGER I
INTEGER I3
INTEGER I5
INTEGER J

I = 0
401   J = I
I = J + 1
501   IF (I-100) 502, 502, 701
502   I3 = 0
J = I / 3 * 3
IF (I - J) 701, 511, 512
511   I3 = 1
512   I5 = 0
J = I / 5 * 5
IF (I - J) 701, 521, 522
521   I5 = 1
522   IF (I3 + I5 - 1) 531, 541, 551
531   WRITE (*, 102), I
GOTO 401
541   IF (I3) 701, 542, 545
542   WRITE (*, 101), 'FIZZ'
GOTO 401
545   WRITE (*, 101), 'BUZZ'
GOTO 401
551   WRITE (*, 101), 'FIZZBUZZ'
GOTO 401

701   STOP
END
``````
A:
``````import sys.stdout as o
for i in range(100):
o.write('\n')
if i % 3 == 0:
o.write('Fizz')
if i % 5 == 0:
o.write('Buzz')
continue
if i % 3 != 0:
o.write(str(i))
o.write('\n')
``````
A:

Python, 97 chars:

``````for i in range(100):
s=''
if not i%3:s+='Fizz'
if not i%5:s+='Buzz'
print(s or i)
``````
A:
``````(0..100).each  { |a|  puts (a%3 == 0 ? "Fizz" : "") + (a%5 == 0 ? "Buzz" : "") + (a%3 != 0 && a%5 != 0 ? a.to_s : "" )
``````
+2  A:

## Python, 64 chars

The shortest Python golf i can come up with (and I haven't seen any shorter w/o the use of `eval`):

``````for n in range(1,101):print'FizzBuzz'[n%3and 4:n%5and 4or 8]or n
``````

Please let me know (by comment) if you know of any shorter.

A:

C# in 87 Characters

``````for(int i=0;i++<100;)
Console.Write("{0:"+(i%3==0?"Fizz":"")+(i%5==0?"Buzz":"")+"} ",i);
``````
A:

A scalable python solution.

``````mods = {'fizz':3,'buzz':5}
keyorder = ['fizz','buzz']

for i in range(1,101):
strs = []
for key in keyorder:
strs.append((i%mods[key]==0) and key or '')
print ''.join(strs) or ('%d' % (i))
``````

Of course, we can scrunch up the loop up for kicks

``````for i in range(1,101):
print ''.join([((i%mods[key]==0) and key or '') for key in keyorder]) or ('%d' % (i))
``````
A:

Here's a quick and straight forward solution in C#:

``````for (int i = 1; i <= 100; i++) Console.WriteLine(i%3 == 0 && i%5 == 0 ? "FizzBuzz" : i%3 == 0 ? "Fizz" : i%5 == 0 ? "Buzz" : i.ToString());
``````
+2  A:

Oracle SQL seems a bit under-represented. Here's a take on it in Oracle, avoiding fancy loops and keeping it to basic selects:

``````select decode(output, null, cast(r as varchar(3)), output) result
from  (Select Rownum r,
decode(mod(rownum, 3), 0, 'Fizz') ||
decode(mod(rownum, 5), 0, 'Buzz') as output
From dual
Connect By Rownum <= 100)a
order by r;
``````

Or another possible solution, requiring more evaluations but no nested selects:

``````Select case when mod(rownum, 3) <> 0 and mod(rownum, 5) <> 0 then cast(rownum as varchar(3))
else (decode(mod(rownum, 3), 0, 'Fizz')
|| decode(mod(rownum, 5), 0, 'Buzz'))
end as output
From dual
Connect By Rownum <= 100;
``````
A:

Newish C:

``````for (int i = 1; i < 101; i++ ) { char s[9]; sprintf(s,"%d", i); char* p = s; if ((i % 3)==0) p=sprintf(p,"Fizz"); if ((i % 5)==0) sprintf(p,"Buzz");   }
``````
A:

A newbie's attempt in C++. Never really done code golf before and not so experienced in programming, so I thought I'd just throw up my own solution. Any feedback would be appreciated. Here goes:

``````#include <iostream>
using namespace std;

int main() {
for (int i=1;i<101;i++) {
if(i%3 == 0 && i%5 == 0) {
cout << "fizzbuzz\n";
}
else if(i%3 == 0) {
cout << "fizz\n";
}
else if(i%5 == 0) {
cout << "buzz\n";
}
else {
cout << i << "\n";
}
}
}
``````

According to gedit, 273 characters including spaces, 191 without. Which is huge compared to anyone else's I've seen :(

A:

Completely uninteresting Python sol'n...

``````for i in range(1,101):
if i % 3 == 0:
if i % 5 == 0:
print("FizzBuzz")
else:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
``````
A:

The shortest C++ solution I could think of...

``````  #include <iostream>
using namespace std;
void main()
{
int i;
for(i=1;i<=100;i++)cout<<(i%3==0?(i%5==0?"FizzBuzz":"Fizz"):(i%5==0?"Buzz":i))<<endl;
}
``````
+1  A:

MSIL, 28 instructions, no locals

I noticed an earlier entry for MSIL by Jon Galloway, which I thought I could throw some time at. This is the result. (I'm not sure if I should be editing his answer since the original question asks about personal solutions, and not a optimized language contest. Writing stuff in someone else's name just feels wrong.)

``````.assembly extern mscorlib {}
.assembly fizzbuzz {.ver 1:0:1:0}
.module fizzbuzz.exe
.method static void main() cil managed {
.entrypoint
.maxstack 3
ldc.i4.0

_beginLoop:
ldc.i4.1

dup
ldc.i4.s 101 // loop end
ceq
brtrue.s _end

dup
ldc.i4.3
rem
brtrue.s _notThree

ldstr "Fizz"
call void [mscorlib]System.Console::Write(string)

_notThree:
dup
ldc.i4.5
rem
brtrue _notFive

ldstr "Buzz"
call void [mscorlib]System.Console::Write(string)

_notFive:
call int32 [mscorlib]System.Console::get_CursorLeft()
brtrue.s _threeOrFive

dup
call void [mscorlib]System.Console::WriteLine(int32)
br.s _beginLoop

_threeOrFive:
call void [mscorlib]System.Console::WriteLine()
br.s _beginLoop

_end:
pop
ret
``````
A:

I never really got into Prolog. Learned it in class, tutored for it, not really my thing. But I still remember enough of it. :)

Not really aiming to golf this but just wanted to answer.

``````% rules
fb(X, fizzbuzz) :- X mod 15 =:= 0, !.
fb(X, buzz) :- X mod 5 =:= 0, !.
fb(X, fizz) :- X mod 3 =:= 0, !.
fb(X, X).

% let's do this
fizzbuzz :- between(1, 100, N),
fb(N, FB),
print(FB),
nl,
false.
``````
+1  A:

Based on this and this I came up with the following idea:

``````class FBFunct():
def __init__(self, start = 1, max = 100):
self.conditions = []
self.start = start
self.max = max

def __call__(self):
for i in range(self.start, self.max + 1):
print(''.join(next(cond) for cond in self.conditions) or i)

self.conditions.append(generator)
``````

The usage is simple:

``````def div3():
while True:
yield ""
yield ""
yield "Fizz"

def div5():
while True:
yield ""
yield ""
yield ""
yield ""
yield "Buzz"

f = FBFunct()
f()
``````
A:

Very straightforward Javascript. Run it in any browser/Firebug/Chrome console

``````for (var i=1 ; i <=100 ; i++)
{
out = ""
if (i%3 == 0)
out = out + "fizz"
if (i%5 == 0)
out = out + "buzz"
if (out == "")
out = i;
document.write(out + "<br>")
}
``````
A:

Here's a golfed up C# code(Btw, this was my first attempt ever at making a FizzBuzz program before finally finding out the powers of the % operator):

``````            for (int i = 1; i < 101; i++)
{

if (((double)i / 3).ToString().Length > 2 && ((double)i / 5).ToString().Length > 2)
{
Console.Write(i.ToString()+"\n");

}
else
{
if (((double)i / 5).ToString().Length == 2 || ((double)i / 5).ToString().Length == 1)
{
Console.Write("Buzz " + i.ToString() + "\n");
if (((double)i / 3).ToString().Length == 2 || ((double)i / 3).ToString().Length == 1)
{
Console.Write("FizzBuzz " + i.ToString() + "\n");

}

}
else
{

if (((double)i / 3).ToString().Length == 2 || ((double)i / 3).ToString().Length == 1)
{
Console.Write("Fizz " + i.ToString() + "\n");
if (((double)i / 5).ToString().Length == 2 || ((double)i / 5).ToString().Length == 1)
{
Console.Write("FizzBuzz " + i.ToString() + "\n");
}
}
else
{
if ((double)(i / 3).ToString().Length == 2 && ((double)i / 5).ToString().Length == 2 || ((double)i / 3).ToString().Length == 1 && ((double)i / 5).ToString().Length == 1)
{
Console.Write("FizzBuzz" + i.ToString() + "\n");

}
}
}
}
}
``````
+2  A:

Perl, 58 chars. No need for any option or feature:

``````print\$_%15?\$_%3?\$_%5?\$_:Buzz:Fizz:FizzBuzz,"\n"for(1..100)
``````

Another revised version (57 chars):

``````print\$_%15?\$_%3?\$_%5?\$_:Buzz:Fizz:FizzBuzz,'
'for(1..100)
``````
+1  A:

``````import Control.Monad.State

fizzbuzz :: Int -> StateT Bool (Writer String) ()
fizzbuzz x = do
when (x `mod` 3 == 0) \$ tell "Fizz" >> put False
when (x `mod` 5 == 0) \$ tell "Buzz" >> put False
get >>= (flip when \$ tell \$ show x)
tell "\n"

main = putStr \$ execWriter \$ mapM_ (flip execStateT True . fizzbuzz) [1..100]
``````
A:

Here's my golfed javascript solutions (works in nodejs, YMMV):

recursive:

``` (function(a){console.log(a%3?"":"Fizz"+a%5?"":"Buzz"||a)a++<99||arguments.callee(a)})(1) ```

For loop:

``` for(a=0;a++<100;)console.log((a%3?"":"Fizz")+(a%5?"":"Buzz")||a) ```

And again in C#:

Recursive:

``` Action<int> f = null; f = n => { Console.WriteLine((n %3 > 0 ? null : ("Fizz" + (n % 5 > 0 ? "" : "Buzz"))) ?? (n + "")); if (n < 100) f(n+1); }; f(1); ```

For loop:

``` for (int n = 0; n++ < 100;) Console.WriteLine((n %3 > 0 ? null : ("Fizz" + (n % 5 > 0 ? "" : "Buzz"))) ?? (n + "")); ```

+1  A:

The bad way ;)

VB.NET .NET 4 - VS 2010

`````` Sub Main()

Dim fizz() As Char =
{"F"c, "i"c, "z"c} ' save 1 char by storing z only once

Dim buzz() As Char =
{"B"c, "u"c} ' cool! save another 2 chars by storing z only once

Dim lettersPrinted As Boolean

For i As Double = 1.0 To 1.0 * 100.0 Step 1 / 2    ' going slowly makes things more secure

lettersPrinted = False

'   only integer numbers, please
If Math.Floor(i) <> i Then Continue For

'   is i divisible by 3?
If Math.Floor(i / 3) = i / 3 Then
Dim fizzIndex As Integer = 0
Console.Write(fizz(fizzIndex))

fizzIndex = fizzIndex + 1
Console.Write(fizz(fizzIndex))

fizzIndex = fizzIndex + 1
Console.Write(fizz(fizzIndex))

'    optimization: do not increment index!
Console.Write(fizz(fizzIndex))

lettersPrinted = True
End If

'   is i divisible by 5?
If Math.Floor(i / 5) = i / 5 Then
Dim buzzIndex As Integer = 0
Dim fizzIndex As Integer = fizz.Length - 1 '  point to last char, which is the letter z

Console.Write(buzz(buzzIndex))

buzzIndex = buzzIndex + 1
Console.Write(buzz(buzzIndex))

'   optimization: write the "z"s in a loop
For j As Integer = 0 To 1
Console.Write(fizz(fizzIndex))
Next

'   optimization: only set letterPrinted to true if it's false
If lettersPrinted = False Then
lettersPrinted = True
Else
'   don't change lettersPrinted
lettersPrinted = lettersPrinted
End If

End If

If lettersPrinted Then
'   nothing to do
Else
Console.Write(i.ToString)
End If

'   new line
Console.WriteLine()

Next i
End Sub
``````
A:

I thought I would go for the straight forward C# Console Application.

``````internal class Program
{
private static void Main(string[] args)
{
for (int i = 1; i <= 100; i++)
{
string message = GetFizzBuzzMessage(i);
Console.WriteLine(message);
}
}

private static string GetFizzBuzzMessage(int i)
{
string message = string.Empty;
if (Equals(i%3, 0))
{
message = "Fizz";
}
if (Equals(i%5, 0))
{
message += "Buzz";
}
if (Equals(message, string.Empty))
{
message = i.ToString();
}
return message;
}
}
``````
A:

Ruby 1.9 Version using External Enumerator (old Generator from 1.8). Inspired by python answer to determine how to perform external iterator (without using a block) in Ruby.

``````div3 = Enumerator.new {|g|
while true
g.yield ""
g.yield ""
g.yield "Fizz"
end
}

div5 = Enumerator.new {|g|
while true
g.yield ""
g.yield ""
g.yield ""
g.yield ""
g.yield "Buzz"
end
}

(1..100).zip(div3,div5).each{|i,fizz,buzz|
tmp = fizz + buzz unless (fizz + buzz).empty? #nil if empty
puts tmp || i
}
``````