What is your solution to the FizzBuzz problem?
[+168] [231] saniul
[2008-08-02 12:53:19]
[ language-agnostic interview-questions code-golf rosetta-stone fizzbuzz ]
[ http://stackoverflow.com/questions/437 ] [DELETED]

See here [1]

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

(15) i'll upvote anyone who posts a working malbolge solution - Claudiu
(18) Greetings, Professor Falken. A strange game. The only winning move is not to play. How about a nice game of chess? - Cameron MacFarland
(7) FizzBuzz is NP-complete, so I doubt you're ever going to solve it. - kubi
[+269] [2008-08-05 04:47:43] Wolfbyte

Golfing is easy. How large can you make it?

Enterprise FizzBuzz [1] 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.

[1] http://code.google.com/p/fizzbuzz/

(1) We need a mod-up for "funny", like /.. :) - Joe Hildebrand
(24) 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 - Wolfbyte
(121) ...Your own joke still makes you laugh? - Michael Myers
(18) 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. - Wolfbyte
(1) That is the most beautiful thing I've seen all week! - Dinah
(34) 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? - John Pirie
(1) Sick. +1 for ya! Still, I am surprised you haven't implemented a client-server architecture, with load sharing as suggested by John. - Sylverdrag
(5) @Sylverdrag - I've ordered a whiteboard but it hasn't arrived yet - Wolfbyte
(1) @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. - Dave Markle
(2) Can you give me a ballpark estimate for porting to J2EE? - Kristopher Johnson
(4) Oooh ESB and J2EE sound like awesome ideas. I'll set up the BizTalk server - Wolfbyte
(3) Sometimes everything that's wrong in the world isn't actually funny at all. - dlamblin
(1) And what about logging? When something goes wrong in production good logs will save you. I suggest log4net logging to a DB backend. - Cameron MacFarland
(21) Oh, and internationalization. How do you handle users in a different language? - Cameron MacFarland
@Cameron that is so true. - Pekka
(1) He laughs because he is legend. - JavaRocky
(8) You are hereby given notice that you violate my patents on both fizzing and buzzing. - Tim Post
This makes me feel very sick ... - Danvil
Where's the factory pattern? - Arron
(1) Hahah, I just came across this! Hilarious :D - Shane
This is brilliant. - Pekka
(1) This project is why YAGNI was created. This one specifically. - Matt Briggs
@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). - SnOrfus
Hahahahaha[haha] - sova
1
[+216] [2008-09-07 11:29:27] gabr

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. :-) - Chris Jester-Young
(13) So simple and elegant! - Cookey
you sir, are a genius! - kronoz
I just think we don't like to type as much ;-) - Pat
(147) Of course I cheated, doh! I wrote a small Delphi program that generated this code. - gabr
(87) This is how you program if you're paid by the line. - Barry Brown
(1) Haven't you heard of loop unrolling?!! duh... - MrDatabase
(63) I'd hire you if you wrote this in an interview. - TM
@gabr: I was just going to ask how long the program to generate that code was :). - xan
10 lines, approx - gabr
(6) 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! - James Anderson
(1) Totally agree. Pfft, loops are for girly men. :) - JavaRocky
(1) That's the exact counterpart of Enterprise FizzBuzz - and exactly as sick... - Danvil
i lol'd :) thanks for this - tenfour
+1 Roll over data driven programming! - MarkJ
:-) This is the best solution i've seen so far. - chris
2
[+153] [2008-08-21 22:12:43] Webjedi

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! ...;) - Kev
Ouch... my frontal lobes hurt! =) - gnovice
(9) ... I love.... *wants to get a .netlolcompiler - Firoso
(3) One of my favorite languages :) - Jonathan Sampson
(1) LOLcode always makes me laugh - Pim Jager
(1) What has the world come to now?!?!??!?! - Maxim Zaslavsky
(101) Really disappointing that SO doesn't have highlighting for this language. - David Winslow
This would be so much easier if lolcode had a modulus. But so much less funny. - Andy
3
[+145] [2008-09-18 09:01:59] ysth

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 - Omer van Kloeten
Yes. Absolutely. - ysth
(55) That is the most bizzare code I've ever seen! It looks more like ascii art than anything that works. +1 for sheer coolness. - The Wicked Flea
(9) prime example of obfuscated code - David McDavidson
(19) Ascii art code...sounds like time for another StackOverflow question... - Slapout
(11) Reminds me of the old IOCCC days... - Kev
BTW where'd you get an ASCII art generator that lets you supply the exact text without breaking the code? - Kev
(7) @Kev: Acme::EyeDrops - ysth
(3) You, sir, are my hero. - Javier Badia
Wicked cool.... - Gab Royer
(2) 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. - David Thornley
IT's been said, but I feel no shame in repeating it. This is really cool. - notJim
(4) Took me a second to realise what I was looking at, then I turn my head on its side and voila, pure awesomeness! :D - Shane
(1) 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. - Stefano Borini
@Stafano Borini: thanks - ysth
4
[+118] [2008-08-21 21:42:33] Lasse V. Karlsen

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. - unwind
And I took the liberty of editing out the extra prints. - recursive
(1) wow really cool! - hasen j
(5) perhaps "A python solution that uses neither division nor modulus:" would be nicer - ShuggyCoUk
(1) Wow this is awesome! - Matt Joiner
This is my favourite solution so far... :) - Yorirou
(4) Cool! You could make it more compact by using the itertools cycle function, allowing e.g. div5 = cycle([''] * 4 + ['Buzz']). - intuited
5
[+104] [2008-08-03 22:04:51] deuseldorf

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


(2) Best way to do it ... let the language compiler/interpretter optimize. Definitely the best way to do it. - Iulian Şerbănoiu
(6) nah. Prakash has it correct. the method here checks divisibility by 3 more often then necessary. - EvilTeach
(33) It feels so much like Python, whoa. - mannicken
(9) 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. - BenAlabaster
(13) For what it's worth, I wrote an interpreter that runs this code: moserware.com/2008/08/meta-fizzbuzz.html - Jeff Moser
6
[+92] [2008-08-07 02:07:56] Michael Stum

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

>++++++++++[<++++++++++>-]>>>+++>+++++>+<<<<<<
[
 >>>+
 >- [<<+>>-]<<<+>[<[-]>>>+<<-]<[>>>+++>>[-]<<<<<- +++++++[>++++++++++<-]>.<+++++++[>+++++<-]>.<++++[>++++<-]>+..[-]<]>>
 >>- [<<<+>>>-]<<<<+>[<[-]>>>>+<<<-]<[>>>>+++++>[-]<<<<<- +++++++++++[>++++++<-]>.<+++++++[>+++++++<-]>++.+++++..[-]<]>>
 >>>
 [-
  <<<[<+>>>>+<<<-]<[>+<-]>>>>
  [
   >++++++++++<
   [>-[>+>+<<-]>[<+>-] +>[<[-]>-]< [>>+<<<++++++++++>-]<<-]
   >---------- >>>[<<<<+>>>>-] <<<<
   >>>>>+> >>[-] <[>+<-] <[>+<-] <<<<< [>>>>>+<<<<<+] <
  ]
  >>>>>
  [ <++++++[>>++++++++<<-]>> . [-] >[<+>-] >[<+>-] <<<-]
  <<<<<
 ]+
 <<<<<
 +++++++++++++.---.[-]
<-]
[1] http://en.wikipedia.org/wiki/Brainfuck
[2] http://koizuka.nowa.jp/entry/146a3d3b33
[3] http://img225.imageshack.us/img225/4416/bffizzbuzzlk5.jpg
[4] http://4mhz.de/bfdev.html

Funniest response I've read in a long time. - Brandon DuRette
(46) you sir... you... are damaged! - DFectuoso
(6) For some reason I thought you meant that BF was underrated because of some Japanese people, so your link was disappointingly juiceless. ;) - Kev
Haha, after reading it again I have to say you're right. Note to self: Less commas, more sentences. - Michael Stum
(9) I think this is in fact a cleverly disguised Whitespace program :D - Jonas Kölker
7
[+92] [2008-10-16 00:58:31] Barry Brown

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

(41) you win ten internets, sir - Carson Myers
(2) Can you send them to my home address? - Barry Brown
(1) Too good! Haha :) - JavaRocky
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> - Evan Plaice
The definition of genius? - Behrooz
I see what you did thar. >_< - Gleno
8
[+74] [2008-09-15 18:37:11] blackwing

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

(12) Brilliant. Really, Brilliant. - DrFloyd5
Yeah. This is nice. - Matthew Schinckel
(4) it would be better without hardcoded constants xD - fortran
This does not solve the task, because it prints till 101 :P - Danvil
(1) @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. - Kimmo Puputti
I stand corrected. - Danvil
Wow. Python without division, modulus, or whitespace. Truly impressive. - Bruce Alderman
You can actually make it slightly shorter by leaving out the 101 in the assignment lines. For example: a[0::3]=['Fizz']*34 - Chris Doggett
9
[+63] [2008-08-02 13:55:54] Michiel de Mare

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

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?

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

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

@lbrandy [2]: 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.

[1] http://codegolf.com/
[2] http://stackoverflow.com/questions/437/#1851

"using ?d for 100 is sinking pretty damn low, IMHO." - and it doesn't work on Ruby 1.9. ?d now evaluates to "d". ;) - Sarah Mei
10
[+56] [2010-04-17 06:02:13] Tor Valamo

HTML/CSS

<!DOCTYPE html>
<html>
    <head>
        <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>
    </head>
    <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>

(1) That's one cool idea! +1 - Boldewyn
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 - Tor Valamo
(2) Awesome. +1 for such a crazy idea! - Duroth
(1) there you go.. made it semantic too :) jsfiddle.net/DXyQ6 - Anurag
Use an OL and you won't need the counter and counter reset. - Kent Brewster
(1) @Kent - you try that and find out why that doesn't work. - Tor Valamo
11
[+51] [2008-08-13 22:52:20] James A. Rosen

My Ook. [1] 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!
[1] http://www.dangermouse.net/esoteric/ook.html

(21) "I don't have a compiler on hand to check it", Ha. - James McMahon
(33) 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" - prestomation
Nice reference, prestomation! - James A. Rosen
(2) bluesorcerer.net/esoteric/ook.html The C# interpreter says Syntax error! - Ed Woodcock
12
[+49] [2008-08-04 20:21:59] vzczc

Excel version

Place this in column B and numbers from 1 to 100 in column A

=IF(MOD(A1,15),IF(MOD(A1,5),IF(MOD(A1,3),A1,"Fizz"),"Buzz"),"FizzBuzz")

I just don't see three Strings. I would've written =IF(MOD(A1,3),"Fizz","") & IF(MOD(A1,5),"Buzz","")... I even think you can leave the "" out. - Yar
Alas, your version does not work - vzczc
It works. You have to put the cursor on cell B1, then use the drag handle to drag all the way down to B100. - Kyralessa
(6) 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.) - Ben Blank
@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
@Nick T, you're right. Here's the OpenOffice fixed version: =IF(NOT(MOD(A1;3)); "fizz";"") & IF(NOT(MOD(A1;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. - Yar
@Daniel 'yar' Rosenstark You need to merge the two lists though; so for one like your form you'd have to add another conditional to check to use the fizz and/or buzz, then populate it with that or the number. E.g. =IF(AND(MOD(ROW(),3),MOD(ROW(),5)),ROW(),IF(NOT(MOD(ROW(),3)), "fizz","") & IF(NOT(MOD(ROW(),5)), "buzz","")) - Nick T
@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. - Yar
13
[+40] [2008-08-04 22:40:05] fastcall

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();

}

(2) FYI: Enumerable.Range requires linq - casademora
(32) In an interview, I'd consider Enumerable.Range to be way overkill. Plain old for (int i = 1; i <= 100; ++i) is sufficient! - Hosam Aly
(9) Uh... this "clean and simple" code is very readably incorrect, as it does not print "FizzBuzz" for numbers divisible by 15. - ShreevatsaR
(75) @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. - Adam V
(8) I would argue then that this isn't as clean and simple as possible, if by simple at least you mean easy to understand. - Joren
(8) Agree with Joren, it works but that optimisation on fizz buzz over 2 lines is ugly. - Pool
@Hosam: I wouldn't consider it overkill. I'd consider it definitive proof that the developer is really a Python programmer who's pretending to be a C# programmer - Yuliy
14
[+38] [2008-08-29 00:35:33] AgentConundrum

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
.

(8) Oh, the memory... and the pain... - Sklivvz
What language is this? - Jim
(9) Aargh... COBOL. I had nearly blocked out my brief, horrifying stint in this language. Thanks. ;) - Adam Lassek
(25) I'm afraid we are going to have to nuke this post from orbit to be safe! - Loren Pechtel
Ditto what Skliwz said. - Slapout
(10) Gah! Where's my silver cross and my garlic?!? - John Pirie
You'd need a somewhat recent computer to fit that FizzBuzz program in memory. - Lars Haugseth
(15) 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+ - NealB
O tempora, o mores! - belisarius
@NealB: I'm honestly not sure whether you're being sarcastic or not. I will tell you that at the time I wrote this abomination, I was working as a COBOL programmer. That said, I really wasn't trying very hard (I wrote it more or less in one pass), and there are more than a few things that are outright wrong in the code that I didn't care to fix when I noticed them. Just a bit of fun. :) - AgentConundrum
Almost all of the answers and comments to this question were in fun. Mine were no different. As a long time COBOL programmer one needs a sense of humor about it, especially if you are maintaining legacy code where unrefenced working storage, dead code an really odd logic "bombs" are everywhere. On a more serious note, the code you posted falls into the "old school" COBOL style. For something a bit more up-to-date see pastebin.com/7xhqshHk. And yes, continue to have fun with COBOL. - NealB
15
[+37] [2008-09-18 13:44:06] David B

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);

(10) You can further reduce the number of symbols by replacing ForEach(s => Console.WriteLine(s)) with simple ForEach(Console.WriteLine). - Mindaugas Mozūras
(1) 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 - David Cuccia
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! ;) - CraigTP
16
[+37] [2009-01-07 22:21:06] Federico Ramponi

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")
match = fbregexp.match(wf.read())
wf.close()
if match:
    print ''.join(match.group(1).split("echo ")).strip()
else:
    print "Unable to fetch fizzbuzz data."

(2) That's awesome xD - poke
(1) Great, "Fizzbuz data" , haha xD - Alessandro Stamatto
I'm in love with this code! - Gleno
you frikin' genius! - vulkanino
Blah blah regex blah blah HTML parser blah blah stackoverflow.com/questions/1732348/… - eyelidlessness
17
[+33] [2008-09-15 17:45:35] Apocalisp

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"]

(16) > but can you generalize it? Ah, a true Haskell programmer... - Andreas Magnusson
(19) No true programmer would write a DestroyBaghdad procedure... - Svante
18
[+33] [2008-08-04 18:09:09] lbrandy

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')


19
[+28] [2008-08-05 18:13:38] Pat

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

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

44 chars.


(1) 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. ;) - Michael Carman
20
[+26] [2008-08-13 22:17:44] Samir

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'
add a,r5
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

(1) good lord that is long! - Karl
(3) Some interesting things going on there with the syntax coloring. - James McMahon
(7) @Karl - That's what she said... (Sorry...) - ChaosPandion
(3) @ChaosPandion: Never apologize for thats what she said! - Matt Briggs
21
[+25] [2008-09-07 19:51:25] Omer van Kloeten

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 :)


(42) I scanned your line as "It's a valid language because I accidentally wrote a compiler for it once." That makes it funny! - Matthew Schinckel
22
[+22] [2008-08-12 06:55:12] Burton

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.


(11) All you people who are checking divisibility 3 times are doing it wrong to begin with. - Jimmy
(16) All you people who are checking divisibility at all are doing it wrong to begin with. - Nikolai Ruhe
23
[+18] [2008-08-07 00:15:34] Patrick

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 [1].

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

[1] http://www.quirkster.com/js/befunge.html

I wrote a smaller version but I can't edit yours, so I posted it as a separate answer. - clahey
Would you measure the size of a Befunge program in non-whitespace characters or in the dimensions of the program? - Chris Lutz
(2) Dimensions of the program. Mainly because that's how the ICFP2006 contest measured 2D programs. - Patrick
Hmm. I tried this in your interpreter but i couldn't get it to work. Maybe i was working it wrong? - RCIX
I just tried it. Works fine. Did you erase the '@' in the box first? - Patrick
+1 for the Monty Python ref. - Blue
24
[+14] [2008-08-06 22:16:08] Jon Galloway

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 counter
ldc.i4.1
stloc.0

br.s _checkEndCondition

_beginLoop:
//Check divisible by three
ldloc.0
ldc.i4.3
rem
ldc.i4.0
ceq
stloc.1

//Check divisible by five
ldloc.0
ldc.i4.5
rem
ldc.i4.0
ceq
stloc.2

//Check if not divisible by three or five
ldloc.1
brtrue.s _checkDivisibleByThree
ldloc.2
brtrue.s _checkDivisibleByThree

//Not divisible by three or five, write counter
ldloc.0
call void [mscorlib]System.Console::WriteLine(int32)
br.s _incrementCounter

_checkDivisibleByThree:
ldloc.1
brfalse.s _checkDivisibleByFive
ldstr "Fizz"
call void [mscorlib]System.Console::Write(string)

_checkDivisibleByFive:
ldloc.2
brfalse.s _newLine
ldstr "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 0x65
blt.s _beginLoop
ret
}

(10) Your family is worried about you - M28
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%. stackoverflow.com/questions/437/… - Simon Svensson
25
[+14] [2008-08-04 18:29:02] Mat
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!)


(2) You can save 4 more characters by removing the quotes around Fizz and Buzz - Greg
+1 for saving a char with the newline. - Ralph
26
[+14] [2008-08-21 21:35:38] tghw

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)]


27
[+13] [2008-08-07 12:35:52] C Hogg

Obligatory Haskell version.

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

i `mod` 15 can't be used as a boolean; you have to say i `mod` 15 == 0 or similar. - Joey Adams
28
[+13] [2008-08-02 23:39:29] Grant

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

#!C:\Python25\python.exe
print """1\n2\nFizz\n4\nBizz\nFizz\n7\n8\nFizz\nBizz
11\nFizz\n13\n14\nFizzBizz\n16\n17\nFizz\n19\nBizz
Fizz\n22\n23\nFizz\nBizz\n26\nFizz\n28\n29\nFizzBizz
31\n32\nFizz\n34\nBizz\nFizz\n37\n38\nFizz\nBizz
41\nFizz\n43\n44\nFizzBizz\n46\n47\nFizz\n49\nBizz
Fizz\n52\n53\nFizz\nBizz\n56\nFizz\n58\n59\nFizzBizz
61\n62\nFizz\n64\nBizz\nFizz\n67\n68\nFizz\nBizz
71\nFizz\n73\n74\nFizzBizz\n76\n77\nFizz\n79\nBizz
Fizz\n82\n83\nFizz\nBizz\n86\nFizz\n88\n89\nFizzBizz
91\n92\nFizz\n94\nBizz\nFizz\n97\n98\nFizz
"""

(2) i dont think thats quite right.. but i agree.. it does give the correct output.. :) +1 - ShoeLace
(11) Wrong. It's 'Buzz', not 'Bizz' - Adriano Varoli Piazza
(13) the interviewer just asked you to change it to 1 to 1000. - 動靜能量
(45) 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. - Grant
(1) That's not nearly as difficult to fix as you make it out to be Jian. Now if he wanted it to skip numbers... - Jimbo
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. - Stefan Kendall
29
[+11] [2009-11-03 00:56:08] Laura

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... - DigitalRoss
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. - Liran Orevi
(3) YOU GO LAURA! Keep it up :) - JavaRocky
Thanks! +1 for being such an encouragement! - Laura
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). - Yorirou
30
[+10] [2008-08-22 16:49:40] btw

Ruby:

require 'rubygems'
require 'fizzbuzz'
puts fizzbuzz

:-D


(3) The FizzBuzz gem is worth reading. It includes a total of 8 solutions, each clever in its own little way. - jleedev
31
[+9] [2008-08-02 13:52:33] Karl Seguin

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

(2) -1 for off-by-one error. The Integer#times method iterates from 0..(n-1); easy fix is to replace 100.times with 1.upto(100). - maerics
0 is falsey, you can drop those `== 0`s. could collapse most of this with interpolation too - Matt Briggs
32
[+9] [2008-08-02 23:17:44] cmcculloh

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 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) - Don Wakefield
lol, yep, this solution is pretty much the basic bare-bones solution... - cmcculloh
33
[+9] [2008-08-06 20:48:10] Coincoin

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)); - Xian
I like it. Btw, you could save one more character with "for(int i=0;++i<101;)" - it depends
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). - it depends
34
[+9] [2009-01-26 12:34:59] community_owned

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 - davewasthere
35
[+8] [2008-08-16 06:50:06] 18hrs

GWBASIC. And Of course, using GOTO statements was mandatory.

10 
20 FOR i=1 TO 100
30 IF (i MOD 3 = 0 )AND (i MOD 5 = 0) THEN GOTO 70
40 IF (i MOD 3 = 0 ) THEN GOTO 90
50 IF (i MOD 5 = 0 ) THEN GOTO 110
55 PRINT i
60 GOTO 120
70 PRINT "FizzBuzz"
80 GOTO 120
90 PRINT "Fizz"
100 GOTO 120
110 PRINT "Buzz"
120 NEXT i

(3) 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) :) - m_oLogin
36
[+7] [2008-08-07 06:21:26] swartzrock

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}

37
[+7] [2008-08-02 15:56:39] Pete

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? - RCIX
38
[+7] [2008-09-06 19:15:01] Don Wakefield

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;
   }
}

(3) Man, I haven't programmed C++ in a long time and this post doesn't make me want to go back! - Alex Baranosky
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. - Don Wakefield
Were you trying to be a hero with that code? - Jimbo
(2) 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'. - Don Wakefield
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 - TokenMacGuy
39
[+7] [2008-08-29 16:21:36] Nathan

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 - tenfour
40
[+7] [2009-09-02 13:50:20] Marcus Andrén

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)

41
[+6] [2010-04-23 03:11:49] Martín Fixman

A LOLCODE [1] 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] http://en.wikipedia.org/wiki/LOLCODE

42
[+6] [2008-09-06 14:33:59] shsteimer

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. :-)


43
[+6] [2008-08-02 23:27:36] akdom

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 Comprehension
print [(((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)]

44
[+6] [2008-08-03 14:49:37] John

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())))); }     

45
[+6] [2008-08-05 08:52:01] Liron Yahdav

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.

46
[+5] [2008-08-05 03:08:40] lbrandy

@Michiel de Mare [1]

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 [2] which was a language invented precisely for this purpose.

Updated: @Michiel de Mare [3] ... 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).

[1] http://stackoverflow.com/questions/437/#453
[2] http://www.golfscript.com/golfscript/index.html
[3] http://stackoverflow.com/questions/437/#453

47
[+5] [2008-08-04 18:46:00] lbrandy

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
[+5] [2008-08-11 13:33:11] AlexCuse

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.


49
[+5] [2008-08-18 02:44:19] slipsec

Powershell:

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

50
[+4] [2008-08-21 12:18:05] seanyboy

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
@[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 ;-) - Steven A. Lowe
51
[+4] [2008-08-02 16:09:51] John

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

52
[+4] [2009-02-26 22:54:55] community_owned

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


53
[+4] [2009-06-07 04:54:59] Chi

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))

54
[+4] [2008-10-02 20:13:26] Eclipse

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 - EvilTeach
55
[+3] [2008-09-23 23:06:08] gbarry
\ FizzBuzz                                     15:18 07Aug08 ...

 : FIZZORBUZZ? ( n --- f     flag says if a F. or B. happened)
                                                      ( n -- )
    FALSE                 \ default=no             ( n F --- )
    OVER                  \ copy arg             ( n F n --- )
    3 /MOD DROP 0 = IF    \ divisible by 3 ?    ( n F f' --- )
      ." Fizz"
      DROP TRUE THEN                                ( n T -- )
    OVER 5 /MOD DROP 0 = IF     \ div by 5?      ( n f f' ---)
      ." Buzz"
      DROP TRUE THEN                               ( n f --- )
    SWAP DROP                                        ( --- f )
 ;

 : FB  120  0 DO
       SPACE
       I FIZZORBUZZ? 0= IF I . THEN
       LOOP
 ;

FB

Am I the last of my kind?

Sorry to confess:
- I never heard of FizzBuzz until Joel told me about it.
- Aftewards, actually went and did this.
- It's FORTH.


It occurred to me to show this again, but in its more renowned "compressed-write-only-no-comments-no-factoring" version.

: FB 120 0 DO SPACE I   FALSE OVER 3 /MOD DROP 0 = IF ." Fizz" DROP TRUE THEN 
 OVER 5 /MOD DROP 0 = IF ." Buzz" DROP TRUE THEN SWAP DROP 0= IF I . THEN LOOP
; FB

56
[+3] [2008-09-24 01:30:54] bk1e

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.


57
[+3] [2008-10-16 01:41:39] Greg Beech

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);

58
[+3] [2008-10-16 02:00:49] Clayton

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 - Matt Briggs
59
[+3] [2008-10-15 10:14:05] Sklivvz

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

60
[+3] [2008-10-16 00:27:14] community_owned

C++:

for (int i=1;i<=100;++i)
    printf((((i%3)&&(i%5))==0)?"%s%s\n":"%s%s%d\n",((i%3)==0)?"Fizz":"",((i%5)==0)?"Buzz":"",i);

C++ Second Example:

for (int i=0;i<100;printf("%s%s%d\n\0%s%s\n"+!(i%3&&i;%5)*8,!(i%3)?"Fizz":"",!(i%5)?"Buzz":"",i,i++));

Modula-2:

MODULE FizzBuzz;

  FORM InOut IMPORT
    WriteLine, WriteInt;

  VAR
    i,m15,m5,m3 : INTEGER;

BEGIN
  FOR i := 1 to 100 DO
    m15 := i MOD 15;
    m5 := i MOD 5;
    m3 := i MOD 3;
    IF m15 = 0 THEN
      WriteLine ( 'FizzBuzz' );
    ELSEIF m5 = 0 THEN
      WriteLine ( 'Buzz' );
    ELSEIF m3 = 0 THEN
      WriteLine ( 'Fizz' );
    ELSE
      WriteInt( i ); WriteLine
    END
  END 
END FizzBuzz.

ADA:

with TEXT_IO;
package int_io is new TEXT_IO.INTEGER_IO( INTEGER);
with TEXT_IO,int_io; use TEXT_IO,int_io;

procudure fizzbuzz is

i,m15,m5,m3 : INTEGER;

begin
 for i in INTEGER range 1 .. 100 loop
   m15 := i mod 15;
   m5 := i mod 5;
   m3 := i mod 3;
   if m15 = 0 then
     PUT ( "FizzBuzz" ); NEW_LINE;
   elseif m5 = 0 then
     PUT ( "Buzz" ); NEW_LINE;
   elseif m3 = 0 then
     PUT ( "Fizz" ); NEW_LINE;
   else
     PUT ( i ); NEW_LINE;
   end if;
 end loop;
end fizzbuzz;

WinBatch (yeah, I know... but I couldn't pass it up):

@echo off
set _i=1
:loop
set /a _return=%_i% %% 15
if /i "%_return%" EQU "0" (
  echo FizzBuzz
  goto :doloop)

set /a _return=%_i% %% 5
if /i "%_return%" EQU "0" (
  echo Buzz
  goto :doloop)

set /a _return=%_i% %% 3
if /i "%_return%" EQU "0" (
  echo Fizz
  goto :doloop)

echo %_i%

:doloop
set _return=
set /a _i += 1
if /i "%_i%" EQU "101" goto :eof
goto :loop

:eof

I have too much time on my hands :D


+1 for variety! - Brian Postow
61
[+3] [2008-10-27 15:18:56] Danko Durbić

In R [1]:

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' )
[1] http://www.r-project.org/

62
[+3] [2008-10-30 18:06:06] Danko Durbić

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="/">
    <!-- Start with 1-->
    <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).


63
[+3] [2009-05-11 16:57:14] Dan

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?


64
[+3] [2009-06-27 20:26:17] Todd Gardner

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) +1 for the sheer line count. I don't care whether it compiles. - RichieHindle
65
[+3] [2008-09-15 14:24:15] dsm

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)))))

66
[+3] [2008-08-30 02:58:05] privatehuff

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)


Just look at the other cobol implementation by @AgentConundrum, a clearly large COBOL shop widow/er - belisarius
67
[+3] [2008-08-28 23:36:32] kronoz

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 - Joel Mueller
68
[+3] [2008-08-25 16:18:48] braklet

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  
}

69
[+3] [2008-08-27 14:26:01] SQLMenace

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

70
[+3] [2008-09-06 20:44:53] warren

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;
}

71
[+3] [2008-09-16 22:21:15] clahey

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+

72
[+3] [2008-08-02 13:21:54] Peter Coulton
<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>

73
[+3] [2008-08-03 17:45:08] Rudd Zwolinski

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 - Steven A. Lowe
74
[+3] [2008-08-05 03:50:19] shsteimer

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("");}
}

75
[+3] [2008-08-05 10:54:41] David

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);
}

76
[+3] [2008-08-05 12:36:16] PabloG

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)


77
[+3] [2008-08-23 02:12:53] Rob Z

Since nobody has done anything with a graphing calculator yet, here's my version in TI-BASIC [1]. 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.

[1] http://en.wikipedia.org/wiki/TI-BASIC

78
[+3] [2008-08-23 03:21:34] James A. Rosen

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.


79
[+3] [2008-08-19 17:50:33] Chuck

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+" ");}

80
[+3] [2008-08-15 21:47:59] Jon Ericson

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

81
[+2] [2008-08-16 19:59:12] Michał Piaskowski

A C version, that does not use division or modulus:

#include 

#define FIZZ 3
#define BUZZ 5
#define MAX 100

int main(int argc, char *argv[])
{
    int i, fizz, buzz;

    fizz = buzz = 1;
    for( i = 1; i 0  && buzz > 0) 
        {
           printf("%d\n",i);
        } 
        else
        {
            if ( fizz == 0)
               printf("Fizz");
            if ( buzz == 0)
               printf("Buzz");

            printf( "\n");
        }

        if (++fizz >= FIZZ) fizz = 0;
        if (++buzz >= BUZZ) buzz = 0;
    }
    return 0;
}

82
[+2] [2008-08-11 18:13:23] Daniel J. Pritchett

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

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 - ShoeLace
83
[+2] [2008-08-08 21:25:12] Mark Renouf

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();
}
}
}

84
[+2] [2008-08-07 11:09:57] Chris Jester-Young

@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 [1] by Scott Meyers (author of the Effective C++ series) that says it much better than I can. :-)

[1] http://www.aristeia.com/Papers/C++ReportColumns/novdec95.pdf

NOTE: it was my understanding that cout will, by default, inject a flush for you when it interpets the '\n' literal. - Aaron
85
[+2] [2008-08-04 14:49:25] Matthew Schinckel

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. - Svante
86
[+2] [2008-08-02 13:16:05] Grant
#!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".


87
[+2] [2008-09-16 14:47:00] dsm

Reply to this post [1] 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)))))))
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem#65048

Macros! Love it. - Apocalisp
88
[+2] [2008-09-17 20:56:06] Eclipse

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%
)

89
[+2] [2008-09-06 22:22:26] paperhorse

Here is another C version which avoids divisions and remainders


#include "stdio.h"
int main(int argc, char **argv) {
    int i,m15,m3;
    for (i=1;i<101;i++) {
        m15=i;
        m15=(m15 & 15)+(m15>>4);
        m15=(m15 & 15)+(m15>>4);
        if (m15==15) printf("FizzBuzz\n");
        else if (m15==10 || m15==5) printf("Buzz\n");
        else {
            m3=m15;
            m3=(m3 & 3)+(m3>>2);
            m3=(m3 & 3)+(m3>>2);
            if (m3==3) printf("Fizz\n");
            else printf("%d\n",i);
        }
    }
    return 0;
}

It actually works by using the equivalent of 9's remainders in hex (15's remainder?) by adding up the hex digits (theres only 2 digits for numbers under 100). I use that for the divisible by 5 (Buzz) and divisible by 15 (FizzBuzz). I then get the base 4 digit sum to find divisibilty by 3 (Fizz).


90
[+2] [2008-09-04 19:01:04] JosephStyons

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.

91
[+2] [2008-09-15 19:43:01] Keith

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

92
[+2] [2008-09-15 20:59:51] hexten

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
  300            ADC #1
  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
  720            ADC #ASC"0"
  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

93
[+2] [2008-09-01 03:30:19] Chris Jester-Young

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

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

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
        add     ax, 0x3030
        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
[1] http://nasm.sourceforge.net/
[2] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/37448#37448

94
[+2] [2008-09-01 04:18:51] Chris Jester-Young

This is a much more jump-happy version of my last submission [1]. 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
        add     al, 0x30
        test    ah, ah
        jz      .onedig
        xchg    ah, al
        add     al, 0x30
        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] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/37420#37420

95
[+2] [2009-06-01 12:41:23] SomeMiscGuy
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);

96
[+2] [2009-06-03 21:20:04] community_owned

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;
}

97
[+2] [2009-06-07 05:32:31] TM

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.... - Roy Rico
98
[+2] [2009-06-24 13:55:56] Kuroki Kaze

PHP, 85 symbols:

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

99
[+2] [2009-06-26 17:18:13] huitseeker

In Ocaml [1].

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;;
[1] http://caml.inria.fr/ocaml/index.en.html

100
[+2] [2009-06-26 18:49:41] Nicolas Dorier

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";
    unit.Namespaces.Add(ns);

    CodeTypeDeclaration fizzBuzzer = new CodeTypeDeclaration("FizzBuzzer");
    ns.Types.Add(fizzBuzzer);

    CodeMemberMethod run = new CodeMemberMethod();
    run.Attributes = MemberAttributes.Static | MemberAttributes.Public;
    run.Name = "Run";
    fizzBuzzer.Members.Add(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);
    fizzBuzzIf.FalseStatements.Add(fizzIf);

    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);
    fizzIf.FalseStatements.Add(buzzIf);
    buzzIf.FalseStatements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(System.Console))), "WriteLine", new CodeVariableReferenceExpression("i")));

    forLoop.Statements.Add(fizzBuzzIf);
    run.Statements.Add(forLoop);

    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] { });
    Console.Read();
}
}

101
[+2] [2009-02-26 23:44:34] community_owned

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; - Matze
102
[+2] [2009-02-04 07:23:56] Rob Boek

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

103
[+2] [2009-01-20 13:43:31] community_owned

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).

104
[+2] [2009-01-26 11:49:34] Andrei Rinea

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);
        }
    }

105
[+2] [2008-09-23 22:56:53] slim

WebMethods Flow.

To be fair, WM lets you write services in Java, but I challenged myself to do FizzBuzz in their Flow doodleware, and to only use the available built-in services.

FizzBuzz in WebMethods Flow

I couldn't find a built in modulus operator, so rather than dividing, multiplying then comparing with the original, I used three counters.

"Unfortunately" you can't see all of the logic - you'd have to click around the UI to see where everything is hidden.


106
[+2] [2009-01-01 10:12:31] tuinstoel

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
/

107
[+2] [2008-12-31 01:50:01] Berk D. Demir

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.


108
[+2] [2008-10-29 11:09:25] AlexJReid

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;

109
[+2] [2008-10-16 17:04:19] community_owned

In OCaml [1]:

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.

[1] http://caml.inria.fr/

Pattern matching, I like - Dan
110
[+2] [2010-05-18 16:27:56] Don

Groovy One-Liner

Can be run in a browser via the Groovy web console [1]

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
}  
[1] http://groovyconsole.appspot.com/

Bonus points for using ?: - Kim Reece
111
[+2] [2010-04-22 16:19:18] Matt Howells

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;
    }
}

112
[+2] [2010-04-08 12:32:40] missingfaktor

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
        }
      )
    }
  }
}

113
[+2] [2010-04-08 12:45:15] Philippe Grondier

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

114
[+2] [2010-06-05 16:49:30] Mattia Gobbi

Some simple python, generalized. Opinions are welcome.

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 - Nas Banov
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 :-) - Mattia Gobbi
115
[+2] [2010-06-18 22:43:34] Na7coldwater

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)​

116
[+2] [2010-06-22 02:04:14] jleedev

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

print '''
eJxNzbsNxDAMA9Ce2+hjfdoU2eUGuCbT52ALOFamKRBPoLg/zwPH9f09OyfqhF2JnI8YxHc8dUBy
Lk1jVajRXGP6gvZ/bgIb2ti2hLHuo7vBSfeAj+6sL8VifY2+Cov0EMTowXokgvUcPQ1JegZy9GS9
FMV6jV6FIr0FPXqz3ok++gufUm5s'''.decode('base64').decode('zlib')
[1] http://stackoverflow.com/questions/584

117
[+2] [2010-06-25 19:42:32] DeadMG

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.


118
[+2] [2010-07-19 00:31:04] Nas Banov

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.


119
[+2] [2010-08-31 16:45:10] sql_mommy

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;

120
[+2] [2009-06-30 16:46:15] community_owned

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

121
[+2] [2009-07-01 22:31:16] Mike Robinson

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


122
[+2] [2009-07-08 11:22:33] cobbal

because golf and J [1] 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] http://jsoftware.com

123
[+2] [2009-11-28 00:53:08] Kragen

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");
    }
}

124
[+2] [2009-12-19 03:25:35] John Sonmez

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));
    }

125
[+2] [2009-09-24 01:56:58] nilamo

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.


126
[+2] [2010-03-03 10:14:19] Michael Pilat

Mathematica: (85 characters)

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

127
[+2] [2010-03-03 15:35:30] Dave Webb

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;

128
[+2] [2009-11-27 23:50:54] Jorge Gajon

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

129
[+2] [2009-10-09 18:55:56] gwell

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"}}

130
[+2] [2010-10-01 09:55:27] OMG_peanuts

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)

131
[+2] [2010-11-03 05:29:58] passcod

The student's choice: CASIO fx-9750G Plus...

For 1->F To 100
F/3=Int(F/3) And F/5!=Int(F/5)=>"FIZZ"
F/5=Int(F/5) And F/3!=Int(F/3)=>"BUZZ"
F/15=Int(F/15)=>"FIZZBUZZ"
F/3!=Int(F/3) And F/5!=Int(F/5)=>F.
Next

Where . is output (disp), / is division, != is not equal, -> is variable assignation, and => is shorthand if.

EDIT:

The above solution is 139 bytes, but it can be optimized to 122 bytes:

For 1->T To 100
If T/15=Int(F/15)
Then "FIZZBUZZ"
Next
IfEnd
If T/3=Int(F/3)
Then "FIZZ"
Next
IfEnd
If T/5=Int(F/5)
Then "BUZZ"
Next
IfEnd
T.
Next

Although this solution seems longer, it contains less instructions and is overall 17 bytes smaller than the previous one.

EDIT 2:

Using a slightly different technique, the program can be even further shortened:

For 1->X To 100
ClrText
" ".
Locate 1,1,X
X/5=Int(X/5)=>Locate 1,1,"    BUZZ"
X/3=Int(X/3)=>Locate 1,1,"FIZZ"
" ".
Next

This version is only 101 bytes long.

EDIT 3:

The program above was still not the best I could do, but the version below sure is:

For 1->X To 10^2
ClrText
Locate 5,1,X
X/3->A
X/5->B
A=Int A=>"FIZZ"
B=Int B=>Locate 5,1,"BUZZ"
Next

Here, 10^ is one symbol. This is the final version: 82 bytes.


132
[+1] [2010-10-11 11:47:34] Pedro Rodrigues

In Haskell:

import Control.Monad.State
import Control.Monad.Trans
import Control.Monad.Writer

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]

133
[+1] [2010-04-08 12:01:27] Patrik

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()));

134
[+1] [2009-11-28 00:04:05] MPelletier

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...


135
[+1] [2009-11-28 00:38:11] Ethan

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;}

136
[+1] [2010-03-17 20:55:57] Will

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++;
}

137
[+1] [2010-03-18 07:45:57] Richard Hein

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);

138
[+1] [2010-03-30 14:23:23] user280448

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);
                    }


                }

139
[+1] [2010-03-30 15:21:53] JonnyLitt
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.''; } } ?>

140
[+1] [2010-03-31 14:30:58] Dan Andreatta

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

141
[+1] [2010-04-01 08:57:14] sum1stolemyname

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++;

142
[+1] [2009-10-04 19:17:16] Ether

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).


143
[+1] [2009-11-26 17:25:53] Yada

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" );

?>

144
[+1] [2010-01-15 15:03:29] Rafael Gaspar

Ruby using Enumerable#collect.

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

145
[+1] [2010-02-04 07:01:43] AdityaGameProgrammer

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);
       }
    }
}

146
[+1] [2010-02-12 06:36:34] Robert

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("");}}

Readable*:

#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.


147
[+1] [2010-02-12 07:44:56] Matias

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!


148
[+1] [2010-02-12 08:52:00] Dave Kirby

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)))

149
[+1] [2010-02-16 23:23:08] Deddo

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

150
[+1] [2010-02-24 19:06:20] Luiscencio

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());}

151
[+1] [2009-07-08 11:33:56] JRL

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 ;-)


152
[+1] [2009-06-30 17:03:00] reinierpost

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. - Ether
But the if () {} else {} phrasing is so obvious it isn't worth posting. - reinierpost
153
[+1] [2009-09-17 01:45:25] GameFreak

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

154
[+1] [2010-09-11 07:38:28] Simon Svensson

MSIL, 28 instructions, no locals

I noticed an earlier entry for MSIL by Jon Galloway [1], 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
        add

        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
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/4059#4059

155
[+1] [2010-09-11 09:55:26] Yorirou

Based on this [1] and this [2] 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)

  def addCondition(self, generator):
    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.addCondition(div3())
f.addCondition(div5())
f()
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/21251#21251
[2] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/65048#65048

156
[+1] [2010-10-12 08:29:16] vulkanino

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

157
[+1] [2010-06-26 05:24:25] Kim Reece

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

158
[+1] [2010-06-22 03:11:07] MatthewD

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. - MatthewD
159
[+1] [2010-06-25 07:22:53] Jonah

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 - Nas Banov
Also Fizzbuzz should be on the same line - Nas Banov
160
[+1] [2010-06-21 07:45:15] Jonas Elfström

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
}

161
[+1] [2010-05-19 12:56:25] stmi

I know that there was already answer with erlang implementation [1], 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)));
par(_) -> badarg.

% 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)));
seq(_) -> badarg.
[1] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem/461315#461315

162
[+1] [2010-06-03 15:38:18] Tom Savage

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);}}

163
[+1] [2010-05-01 00:01:18] David

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! - Gregory Higley
164
[+1] [2008-10-16 17:33:29] jim

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. - tuinstoel
165
[+1] [2008-10-01 17:29:13] Gustavo Carreno

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";
}
?>

166
[+1] [2008-10-04 17:19:14] cmcculloh

Ok, here's a recursive solution based on my JavaScript solution [1]. 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] http://stackoverflow.com/questions/437/what-is-your-solution-to-the-fizzbuzz-problem#577

167
[+1] [2008-10-15 09:52:57] Gregory Higley

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]
    ]
]

168
[+1] [2008-12-31 04:08:10] vg1890

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

169
[+1] [2008-12-31 10:58:11] Øyvind Skaar

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">
    <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>

170
[+1] [2008-12-31 17:49:26] kwako

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";

171
[+1] [2009-06-28 00:49:12] Isaac Waller

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....


172
[+1] [2009-06-30 16:39:44] community_owned

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

173
[+1] [2008-09-04 18:44:50] DrFloyd5

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!


174
[+1] [2008-08-28 16:41:00] user3451

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.


175
[+1] [2008-09-15 14:38:25] Farrel

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

176
[+1] [2008-09-06 15:43:39] billpg

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. - Jon Purdy
177
[+1] [2008-09-06 17:54:01] J.F. Sebastian

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));
}

178
[+1] [2008-09-06 19:50:02] Jeremy Banks

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

179
[+1] [2008-09-16 12:29:46] community_owned

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) }

180
[+1] [2008-09-17 16:16:31] tucuxi

Yet another C version (77 chars). People at anarchy golf [1] 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");}
[1] http://www.shinh.org/l.rb?c

181
[+1] [2008-09-23 21:45:35] Andrea Ambu

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

182
[+1] [2008-09-18 13:21:29] Porges

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")] (++)

183
[+1] [2008-08-02 14:09:38] Prakash

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");