FizzBuzz: Difference between revisions
Added XLISP |
|||
Line 6,026: | Line 6,026: | ||
(defun fizzb (x y) |
(defun fizzb (x y) |
||
(display (cond |
(display (cond |
||
((= (mod x 3) (mod x 5) 0) "FizzBuzz") |
|||
((= (mod x 3) 0) "Fizz") |
((= (mod x 3) 0) "Fizz") |
||
((= (mod x 5) 0) "Buzz") |
((= (mod x 5) 0) "Buzz") |
Revision as of 05:17, 19 August 2016
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
- for multiples of three, print Fizz (instead of the number)
- for multiples of five, print Buzz (instead of the number)
- for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
- Also see
- (a blog) dont-overthink-fizzbuzz
- (a blog) fizzbuzz-the-programmers-stairway-to-heaven
360 Assembly
6502 Assembly
68000 Assembly
8086 Assembly
8th
<lang forth> with: n
- num? \ n f -- )
if drop else . then ;
\ is m mod n 0? leave the result twice on the stack
- div? \ m n -- f f
mod 0 = dup ;
- fizz? \ n -- n f
dup 3 div? if "Fizz" . then ;
- buzz? \ n f -- n f
over 5 div? if "Buzz" . then or ;
\ print a message as appropriate for the given number:
- fizzbuzz \ n --
fizz? buzz? num? space ;
\ iterate from 1 to 100: ' fizzbuzz 1 100 loop cr bye </lang>
ABAP
<lang>DATA: tab TYPE TABLE OF string.
tab = VALUE #(
FOR i = 1 WHILE i <= 100 ( COND string( LET r3 = i MOD 3 r5 = i MOD 5 IN WHEN r3 = 0 AND r5 = 0 THEN |FIZZBUZZ| WHEN r3 = 0 THEN |FIZZ| WHEN r5 = 0 THEN |BUZZ| ELSE i ) ) ).
cl_demo_output=>write( tab ). cl_demo_output=>display( ).</lang>
ACL2
<lang Lisp>(defun fizzbuzz-r (i)
(declare (xargs :measure (nfix (- 100 i)))) (prog2$ (cond ((= (mod i 15) 0) (cw "FizzBuzz~%")) ((= (mod i 5) 0) (cw "Buzz~%")) ((= (mod i 3) 0) (cw "Fizz~%")) (t (cw "~x0~%" i))) (if (zp (- 100 i)) nil (fizzbuzz-r (1+ i)))))
(defun fizzbuzz () (fizzbuzz-r 1))</lang>
ActionScript
The ActionScript solution works just like the JavaScript solution (they share the ECMAScript specification). The difference is that ActionScript has the trace command to write out to a console. <lang actionscript>for (var i:int = 1; i <= 100; i++) {
if (i % 15 == 0) trace('FizzBuzz'); else if (i % 5 == 0) trace('Buzz'); else if (i % 3 == 0) trace('Fizz'); else trace(i);
}</lang>
Ada
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
procedure Fizzbuzz is begin
for I in 1..100 loop if I mod 15 = 0 then Put_Line("FizzBuzz"); elsif I mod 5 = 0 then Put_Line("Buzz"); elsif I mod 3 = 0 then Put_Line("Fizz"); else Put_Line(Integer'Image(I)); end if; end loop;
end Fizzbuzz;</lang>
ALGOL 68
<lang algol68>main:(
FOR i TO 100 DO printf(($gl$, IF i %* 15 = 0 THEN "FizzBuzz" ELIF i %* 3 = 0 THEN "Fizz" ELIF i %* 5 = 0 THEN "Buzz" ELSE i FI )) OD
)</lang> or simply: <lang algol68>FOR i TO 100 DO print(((i%*15=0|"FizzBuzz"|:i%*3=0|"Fizz"|:i%*5=0|"Buzz"|i),new line)) OD</lang>
ALGOL W
<lang algolw> begin
i_w := 1; % set integers to print in minimum space % for i := 1 until 100 do begin if i rem 15 = 0 then write( "FizzBuzz" ) else if i rem 5 = 0 then write( "Buzz" ) else if i rem 3 = 0 then write( "Fizz" ) else write( i ) end for_i
end.</lang>
AntLang
<lang AntLang>n:{1+ x}map range[100] s:{a:0eq x mod 3;b:0eq x mod 5;concat apply{1elem x}map{0elem x}hfilter seq[1- max[a;b];a;b]merge seq[str[x];"Fizz";"Buzz"]}map n echo map s</lang>
APEX
<lang Apex> for(integer i=1; i <= 100; i++){
String output = ; if(math.mod(i, 3) == 0) output += 'Fizz'; if(math.mod(i, 5) == 0) output += 'Buzz'; if(output != ){ System.debug(output); } else { System.debug(i); }
} </lang>
APL
<lang apl>⎕IO←0 (L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100] </lang>
Slightly different approach that makes use of the Decode function (⊥):
<lang apl>
A[I]←1+I←(0⍷A)/⍳⍴A←('FIZZBUZZ' 'FIZZ’ 'BUZZ' 0)[2⊥¨×(⊂3 5)|¨1+⍳100]
</lang>
The idea is to first calculate the residues for all numbers 1..100 after division with both 3 and 5. This generates 100 pairs of numbers a b, where a is either 0,1,2 and b is either 0,1,2,3,4.
These pairs are then put through the sign function which returns 0 for a 0, and a 1 for anything greater than 0. Now we have binary pairs. The binary pairs are encoded with a left argument of 2 resulting in 0,1,2,3. These are treated as indices for the "FizzBuzz vector" where 0 is in position 3.
Variable A holds this new vector of words and zeros. Variable I is assigned the zeros' positions. Finally A[I] is replaced with corresponding indices.
If you have an aversion against mixed vectors, consider inserting ⍕¨ before the final (i.e. left-most) assignment.
Here's a Dyalog-specific solution taking advantage of its anonymous function extension:
<lang apl>{ ⍵ 'Fizz' 'Buzz' 'FizzBuzz'[ +/1 2×0=3 5|⍵] }¨1+⍳100</lang>
AppleScript
<lang AppleScript>property outputText: "" repeat with i from 1 to 100
if i mod 15 = 0 then set outputText to outputText & "FizzBuzz" else if i mod 3 = 0 then set outputText to outputText & "Fizz" else if i mod 5 = 0 then set outputText to outputText & "Buzz" else set outputText to outputText & i end if set outputText to outputText & linefeed
end repeat outputText</lang>
Or, using map(), range(), and a more functional pattern of composition:
<lang AppleScript>on run
intercalate(linefeed, ¬ map(fizzBuzz, range(1, 100)))
end run
-- fizzBuzz :: Int -> String
on fizzBuzz(x)
caseOf(x, [[my fizzAndBuzz, "FizzBuzz"], ¬ [my fizz, "Fizz"], ¬ [my buzz, "Buzz"]], ¬ x as string)
end fizzBuzz
-- fizzAndBuzz :: Int -> Bool
on fizzAndBuzz(n)
n mod 15 = 0
end fizzAndBuzz
-- fizz :: Int -> Bool on fizz(n)
n mod 3 = 0
end fizz
-- buzz :: Int -> Bool on buzz(n)
n mod 5 = 0
end buzz
-- GENERIC LIBRARY FUNCTIONS
-- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined
end intercalate
-- map :: (a -> b) -> [a] -> [b] on map(f, xs)
set mf to mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to mf's lambda(item i of xs, i, xs) end repeat return lst
end map
-- caseOf :: a -> [(predicate, b)] -> Maybe b -> Maybe b on caseOf(e, lstPV, default)
repeat with lstCase in lstPV set {p, v} to contents of lstCase if mReturn(p)'s lambda(e) then return v end repeat return default
end caseOf
-- m..n -- Int -> Int -> Int on range(m, n)
set lng to (n - m) + 1 set base to m - 1 set lst to {} repeat with i from 1 to lng set end of lst to i + base end repeat return lst
end range
-- Lift 2nd class function into 1st class wrapper
-- handler function --> first class script object
on mReturn(f)
if class of f is script then return f script property lambda : f end script
end mReturn</lang>
Applesoft BASIC
See FizzBuzz/Basic
Arbre
<lang Arbre>fizzbuzz():
for x in [1..100] if x%5==0 and x%3==0 return "FizzBuzz" else if x%3==0 return "Fizz" else if x%5==0 return "Buzz" else return x
main():
fizzbuzz() -> io</lang>
Arc
Arc 3.1 Base
<lang lisp>(for n 1 100
(prn:if (multiple n 15) 'FizzBuzz (multiple n 5) 'Buzz (multiple n 3) 'Fizz n))</lang>
<lang lisp>(for n 1 100
(prn:check (string (when (multiple n 3) 'Fizz) (when (multiple n 5) 'Buzz)) ~empty n)) ; check created string not empty, else return n</lang>
Waterhouse Arc
<lang lisp>(for n 1 100
(prn:case (gcd n 15) 1 n 3 'Fizz 5 'Buzz 'FizzBuzz))</lang>
AutoHotkey
Search autohotkey.com: [1]
<lang AutoHotkey>Loop, 100
{
If (Mod(A_Index, 15) = 0) output .= "FizzBuzz`n" Else If (Mod(A_Index, 3) = 0) output .= "Fizz`n" Else If (Mod(A_Index, 5) = 0) output .= "Buzz`n" Else output .= A_Index "`n"
} FileDelete, output.txt FileAppend, %output%, output.txt Run, cmd /k type output.txt</lang> A short example with cascading ternary operators and graphical output. Press Esc to close the window. <lang AutoHotkey>Gui, Add, Edit, r20 Gui,Show Loop, 100
Send, % (!Mod(A_Index, 15) ? "FizzBuzz" : !Mod(A_Index, 3) ? "Fizz" : !Mod(A_Index, 5) ? "Buzz" : A_Index) "`n"
Return Esc:: ExitApp</lang>
AutoIt
Example1
Output via MsgBox(): <lang AutoIt>For $i = 1 To 100 If Mod($i, 15) = 0 Then MsgBox(0, "FizzBuzz", "FizzBuzz") ElseIf Mod($i, 5) = 0 Then MsgBox(0, "FizzBuzz", "Buzz") ElseIf Mod($i, 3) = 0 Then MsgBox(0, "FizzBuzz", "Fizz") Else MsgBox(0, "FizzBuzz", $i) EndIf Next</lang>
Example2
Output via console, logfile and/or messagebox: <lang AutoIt>#include <Constants.au3>
- uncomment how you want to do the output
Func Out($Msg) ConsoleWrite($Msg & @CRLF)
- ~ FileWriteLine("FizzBuzz.Log", $Msg)
- ~ $Btn = MsgBox($MB_OKCANCEL + $MB_ICONINFORMATION, "FizzBuzz", $Msg)
- ~ If $Btn > 1 Then Exit ; Pressing 'Cancel'-button aborts the program
EndFunc ;==>Out
Out("# FizzBuzz:") For $i = 1 To 100 If Mod($i, 15) = 0 Then Out("FizzBuzz") ElseIf Mod($i, 5) = 0 Then Out("Buzz") ElseIf Mod($i, 3) = 0 Then Out("Fizz") Else Out($i) EndIf Next Out("# Done.")</lang>
AWK
See FizzBuzz/AWK
Axe
<lang axe>For(I,1,100) !If I^3??I^5
Disp "FIZZBUZZ",i
Else!If I^3
Disp "FIZZ",i
Else!If I^5
Disp "BUZZ",i
Else
Disp I▶Dec,i
End .Pause to allow the user to actually read the output Pause 1000 End</lang>
Babel
<lang babel>main:
{ { iter 1 + dup 15 % { "FizzBuzz" << zap } { dup 3 % { "Fizz" << zap } { dup 5 % { "Buzz" << zap} { %d << } if } if } if
"\n" << }
100 times }</lang>
bash
Any bash hacker would do this as a one liner at the shell, so... <lang bash>for n in {1..100}; do ((( n % 15 == 0 )) && echo 'FizzBuzz') || ((( n % 5 == 0 )) && echo 'Buzz') || ((( n % 3 == 0 )) && echo 'Fizz') || echo $n; done</lang> For the sake of readability... <lang bash>for n in {1..100}; do
((( n % 15 == 0 )) && echo 'FizzBuzz') || ((( n % 5 == 0 )) && echo 'Buzz') || ((( n % 3 == 0 )) && echo 'Fizz') || echo $n;
done</lang> Here's a very concise approach, with only 75 characters total. Unfortunately it relies on aspects of Bash which are rarely used. <lang bash>for i in {1..100};do((i%3))&&x=||x=Fizz;((i%5))||x+=Buzz;echo ${x:-$i};done</lang> Here's the concise approach again, this time separated into multiple lines. <lang bash># FizzBuzz in Bash. A concise version, but with verbose comments. for i in {1..100} # Use i to loop from "1" to "100", inclusive. do ((i % 3)) && # If i is not divisible by 3...
x= || # ...blank out x (yes, "x= " does that). Otherwise,... x=Fizz # ...set (not append) x to the string "Fizz". ((i % 5)) || # If i is not divisible by 5, skip (there's no "&&")... x+=Buzz # ...Otherwise, append (not set) the string "Buzz" to x. echo ${x:-$i} # Print x unless it is blanked out. Otherwise, print i.
done</lang> It's a bit silly to optimize such a small & fast program, but for the sake of algorithm analysis it's worth noting that the concise approach is reasonably efficient in several ways. Each divisibility test appears in the code exactly once, only two variables are created, and the approach avoids setting variables unnecessarily. As far as I can tell, the divisibility tests only fire the minimum number of times required for the general case (e.g. where the 100/3/5 constants can be changed), unless you introduce more variables and test types. Corrections invited. I avoided analyzing the non-general case where 100/3/5 never change, because one "optimal" solution is to simply print the pre-computed answer,
BASIC
See FizzBuzz/Basic
Batch File
FOR /L version:
<lang dos>@echo off for /L %%i in (1,1,100) do call :tester %%i goto :eof
- tester
set /a test = %1 %% 15 if %test% NEQ 0 goto :NotFizzBuzz echo FizzBuzz goto :eof
- NotFizzBuzz
set /a test = %1 %% 5 if %test% NEQ 0 goto :NotBuzz echo Buzz goto :eof
- NotBuzz
set /a test = %1 %% 3 if %test% NEQ 0 goto :NotFizz echo Fizz goto :eof
- NotFizz
echo %1
</lang>
Loop version:
<lang dos>@echo off set n=1
- loop
call :tester %n% set /a n += 1 if %n% LSS 101 goto loop goto :eof
- tester
set /a test = %1 %% 15 if %test% NEQ 0 goto :NotFizzBuzz echo FizzBuzz goto :eof
- NotFizzBuzz
set /a test = %1 %% 5 if %test% NEQ 0 goto :NotBuzz echo Buzz goto :eof
- NotBuzz
set /a test = %1 %% 3 if %test% NEQ 0 goto :NotFizz echo Fizz goto :eof
- NotFizz
echo %1</lang>
FOR /L with a block instead of very-high-overhead subroutine call:
<lang dos>@echo off & setlocal enabledelayedexpansion for /l %%i in (1,1,100) do (
set /a m5=%%i %% 5 set /a m3=%%i %% 3 set s= if !m5! equ 0 set s=!s!Fizz if !m3! equ 0 set s=!s!Buzz if "!s!"=="" set s=%%i echo !s!
)</lang>
BBC BASIC
See FizzBuzz/Basic
bc
This solution never uses else, because bc has no else keyword (but some implementations add else as an extension).
<lang bc>for (i = 1; i <= 100; i++) { w = 0 if (i % 3 == 0) { "Fizz"; w = 1; } if (i % 5 == 0) { "Buzz"; w = 1; } if (w == 0) i if (w == 1) " " } quit</lang>
beeswax
“Ordinary” FizzBuzz solution:
<lang beeswax> > q
>@F5~%"d@F{ > @F q
_1>F3~%'d`Fizz`@F5~%'d >`Buzz`@FNp
;bL@~.~4~.5~5@ P<</lang>
Example without double mod 5 check, using a flag instead, to check if Fizz already got printed (in this case the number n must not be printed if mod 5 is > 0):
<lang beeswax> >@?q
> q >Ag'd@{?p
_>"1F3~%'d`Fizz`f>@F5~%'d`Buzz`@p
b P~;"-~@~.+0~P9@N?<</lang>
Befunge
See FizzBuzz/EsoLang
Boo
<lang boo>def fizzbuzz(size):
for i in range(1, size): if i%15 == 0: print 'FizzBuzz' elif i%5 == 0: print 'Buzz' elif i%3 == 0: print 'Fizz' else: print i
fizzbuzz(101)</lang>
Bracmat
<lang bracmat>0:?i&whl'(1+!i:<101:?i&out$(mod$(!i.3):0&(mod$(!i.5):0&FizzBuzz|Fizz)|mod$(!i.5):0&Buzz|!i))</lang> Same code, pretty printed: <lang bracmat> 0:?i & whl
' ( 1+!i:<101:?i & out $ ( mod$(!i.3):0 & ( mod$(!i.5):0&FizzBuzz | Fizz ) | mod$(!i.5):0&Buzz | !i ) )</lang>
Brat
<lang brat>1.to 100 { n |
true? n % 15 == 0 { p "FizzBuzz" } { true? n % 3 == 0 { p "Fizz" } { true? n % 5 == 0 { p "Buzz" } { p n } } } }</lang>
Brainf***
See FizzBuzz/EsoLang
C
One line version, with pretty printing <lang c>#include <stdio.h>
int main() {
for (int i=1; i<=105; i++) if (i%3 && i%5) printf("%3d ", i); else printf("%s%s%s", i%3?"":"Fizz", i%5?"":"Buzz", i%15?" ":"\n");
} </lang>
<lang c>#include<stdio.h>
int main (void) {
int i; for (i = 1; i <= 100; i++) { if (!(i % 15)) printf ("FizzBuzz"); else if (!(i % 3)) printf ("Fizz"); else if (!(i % 5)) printf ("Buzz"); else printf ("%d", i);
printf("\n"); } return 0;
}</lang> Implicit int main and return 0 (C99+): <lang c>#include <stdio.h>
main() {
int i = 1; while(i <= 100) { if(i % 15 == 0) puts("FizzBuzz"); else if(i % 3 == 0) puts("Fizz"); else if(i % 5 == 0) puts("Buzz"); else printf("%d\n", i); i++; }
}</lang> obfuscated: <lang c>#include <stdio.h>
- define F(x,y) printf("%s",i%x?"":#y"zz")
int main(int i){for(--i;i++^100;puts(""))F(3,Fi)|F(5,Bu)||printf("%i",i);return 0;}</lang>
This actually works (the array init part, saves 6 bytes of static data, whee):<lang c>#include<stdio.h>
int main () { int i; const char *s[] = { "%d\n", "Fizz\n", s[3] + 4, "FizzBuzz\n" }; for (i = 1; i <= 100; i++) printf(s[!(i % 3) + 2 * !(i % 5)], i);
return 0; }</lang>
With numbers theory: <lang c>#include <stdio.h>
int main(void) {
for (int i = 1; i <= 100; ++i) { if (i % 3 == 0) printf("fizz"); if (i % 5 == 0) printf("buzz"); if (i * i * i * i % 15 == 1) printf("%d", i); puts(""); }
} </lang>
Without conditionals, anything in the loop body gcc compiles with branching, duplicate tests or duplicate strings. Depends on ASCII and two's complement arithmetic:
<lang c>#include <stdio.h> int main() {
for (int i=0;++i<101;puts("")) { char f[] = "FizzBuzz%d"; f[8-i%5&12]=0; printf (f+(-i%3&4+f[8]/8), i); }
} </lang>
C++
<lang cpp>#include <iostream>
using namespace std; int main () {
for (int i = 1; i <= 100; i++) { if ((i % 15) == 0) cout << "FizzBuzz\n"; else if ((i % 3) == 0) cout << "Fizz\n"; else if ((i % 5) == 0) cout << "Buzz\n"; else cout << i << "\n"; } return 0;
}</lang> Alternate version not using modulo 15: <lang cpp>#include <iostream> using namespace std;
int main() {
for (int i = 0; i <= 100; ++i) { bool fizz = (i % 3) == 0; bool buzz = (i % 5) == 0; if (fizz) cout << "Fizz"; if (buzz) cout << "Buzz"; if (!fizz && !buzz) cout << i; cout << "\n"; } return 0;
}</lang>
Alternate version that avoids using modulo. (Modulo can be expensive on some architectures.) <lang cpp>#include <iostream>
int main() {
int i, f = 2, b = 4;
for ( i = 1 ; i <= 100 ; ++i, --f, --b ) { if ( f && b ) { std::cout << i; } if ( !f ) { std::cout << "Fizz"; f = 3; } if ( !b ) { std::cout << "Buzz"; b = 5; } std::cout << std::endl; }
return 0;
} </lang>
A version using std::transform:
<lang cpp>#include <iostream>
- include <algorithm>
- include <vector>
int main() {
std::vector<int> range(100); std::iota(range.begin(), range.end(), 1);
std::vector<std::string> values; values.resize(range.size());
auto fizzbuzz = [](int i) -> std::string { if ((i%15) == 0) return "FizzBuzz"; if ((i%5) == 0) return "Buzz"; if ((i%3) == 0) return "Fizz"; return std::to_string(i); };
std::transform(range.begin(), range.end(), values.begin(), fizzbuzz);
for (auto& str: values) std::cout << str << std::endl;
return 0;
}</lang> Version computing FizzBuzz at compile time with metaprogramming: <lang cpp>#include <iostream>
template <int n, int m3, int m5> struct fizzbuzz : fizzbuzz<n-1, (n-1)%3, (n-1)%5> {
fizzbuzz() { std::cout << n << std::endl; }
};
template <int n> struct fizzbuzz<n, 0, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5> {
fizzbuzz() { std::cout << "FizzBuzz" << std::endl; }
};
template <int n, int p> struct fizzbuzz<n, 0, p> : fizzbuzz<n-1, (n-1)%3, (n-1)%5> {
fizzbuzz() { std::cout << "Fizz" << std::endl; }
};
template <int n, int p> struct fizzbuzz<n, p, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5> {
fizzbuzz() { std::cout << "Buzz" << std::endl; }
};
template <> struct fizzbuzz<0,0,0> {
fizzbuzz() { std::cout << 0 << std::endl; }
};
template <int n> struct fb_run {
fizzbuzz<n, n%3, n%5> fb;
};
int main() {
fb_run<100> fb; return 0;
}</lang> Hardcore templates (compile with -ftemplate-depth-9000 -std=c++0x): <lang cpp>#include <iostream>
- include <string>
- include <cstdlib>
- include <boost/mpl/string.hpp>
- include <boost/mpl/fold.hpp>
- include <boost/mpl/size_t.hpp>
using namespace std; using namespace boost;
/////////////////////////////////////////////////////////////////////////////// // exponentiation calculations template <int accum, int base, int exp> struct POWER_CORE : POWER_CORE<accum * base, base, exp - 1>{};
template <int accum, int base> struct POWER_CORE<accum, base, 0> {
enum : int { val = accum };
};
template <int base, int exp> struct POWER : POWER_CORE<1, base, exp>{};
/////////////////////////////////////////////////////////////////////////////// // # of digit calculations template <int depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_CORE<depth + 1, i / 10>{};
template <int depth> struct NUM_DIGITS_CORE<depth, 0> {
enum : int { val = depth};
};
template <int i> struct NUM_DIGITS : NUM_DIGITS_CORE<0, i>{};
template <> struct NUM_DIGITS<0> {
enum : int { val = 1 };
};
/////////////////////////////////////////////////////////////////////////////// // Convert digit to character (1 -> '1') template <int i> struct DIGIT_TO_CHAR {
enum : char{ val = i + 48 };
};
/////////////////////////////////////////////////////////////////////////////// // Find the digit at a given offset into a number of the form 0000000017 template <unsigned int i, int place> // place -> [0 .. 10] struct DIGIT_AT {
enum : char{ val = (i / POWER<10, place>::val) % 10 };
};
struct NULL_CHAR {
enum : char{ val = '\0' };
};
/////////////////////////////////////////////////////////////////////////////// // Convert the digit at a given offset into a number of the form '0000000017' to a character template <unsigned int i, int place> // place -> [0 .. 9]
struct ALT_CHAR : DIGIT_TO_CHAR< DIGIT_AT<i, place>::val >{};
/////////////////////////////////////////////////////////////////////////////// // Convert the digit at a given offset into a number of the form '17' to a character
// Template description, with specialization to generate null characters for out of range offsets template <unsigned int i, int offset, int numDigits, bool inRange>
struct OFFSET_CHAR_CORE_CHECKED{};
template <unsigned int i, int offset, int numDigits>
struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, false> : NULL_CHAR{};
template <unsigned int i, int offset, int numDigits>
struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, true> : ALT_CHAR<i, (numDigits - offset) - 1 >{};
// Perform the range check and pass it on template <unsigned int i, int offset, int numDigits>
struct OFFSET_CHAR_CORE : OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, offset < numDigits>{};
// Calc the number of digits and pass it on template <unsigned int i, int offset>
struct OFFSET_CHAR : OFFSET_CHAR_CORE<i, offset, NUM_DIGITS::val>{};
/////////////////////////////////////////////////////////////////////////////// // Integer to char* template. Works on unsigned ints. template <unsigned int i> struct IntToStr {
const static char str[]; typedef typename mpl::string< OFFSET_CHAR<i, 0>::val, OFFSET_CHAR<i, 1>::val, OFFSET_CHAR<i, 2>::val, OFFSET_CHAR<i, 3>::val, OFFSET_CHAR<i, 4>::val, OFFSET_CHAR<i, 5>::val, /*OFFSET_CHAR<i, 6>::val, OFFSET_CHAR<i, 7>::val, OFFSET_CHAR<i, 8>::val, OFFSET_CHAR<i, 9>::val,*/ NULL_CHAR::val>::type type;
};
template <unsigned int i> const char IntToStr::str[] = {
OFFSET_CHAR<i, 0>::val, OFFSET_CHAR<i, 1>::val, OFFSET_CHAR<i, 2>::val, OFFSET_CHAR<i, 3>::val, OFFSET_CHAR<i, 4>::val, OFFSET_CHAR<i, 5>::val, OFFSET_CHAR<i, 6>::val, OFFSET_CHAR<i, 7>::val, OFFSET_CHAR<i, 8>::val, OFFSET_CHAR<i, 9>::val, NULL_CHAR::val
};
template <bool condition, class Then, class Else> struct IF {
typedef Then RET;
};
template <class Then, class Else> struct IF<false, Then, Else> {
typedef Else RET;
};
template < typename Str1, typename Str2 >
struct concat : mpl::insert_range<Str1, typename mpl::end<Str1>::type, Str2> {};
template <typename Str1, typename Str2, typename Str3 >
struct concat3 : mpl::insert_range<Str1, typename mpl::end<Str1>::type, typename concat<Str2, Str3 >::type > {};
typedef typename mpl::string<'f','i','z','z'>::type fizz; typedef typename mpl::string<'b','u','z','z'>::type buzz; typedef typename mpl::string<'\r', '\n'>::type mpendl; typedef typename concat<fizz, buzz>::type fizzbuzz;
// discovered boost mpl limitation on some length
template <int N> struct FizzBuzz {
typedef typename concat3<typename FizzBuzz<N - 1>::type, typename IF<N % 15 == 0, typename fizzbuzz::type, typename IF<N % 3 == 0, typename fizz::type, typename IF<N % 5 == 0, typename buzz::type, typename IntToStr<N>::type >::RET >::RET >::RET, typename mpendl::type>::type type;
};
template <> struct FizzBuzz<1> {
typedef mpl::string<'1','\r','\n'>::type type;
};
int main(int argc, char** argv) {
const int n = 7; std::cout << mpl::c_str<FizzBuzz<n>::type>::value << std::endl;
return 0; }</lang> Note: it takes up lots of memory and takes several seconds to compile. To enable compilation for 7 < n <= 25, please, modify include/boost/mpl/limits/string.hpp BOOST_MPL_LIMIT_STRING_SIZE to 128 instead of 32).
C#
<lang csharp>class Program {
static void Main() { for (uint i = 1; i <= 100; i++) { string s = null;
if (i % 3 == 0) s = "Fizz";
if (i % 5 == 0) s += "Buzz";
System.Console.WriteLine(s ?? i.ToString()); } }
}</lang> <lang csharp>using System; using System.Linq;
namespace FizzBuzz {
class Program { static void Main(string[] args) { Enumerable.Range(1, 100) .Select(a => String.Format("{0}{1}", a % 3 == 0 ? "Fizz" : string.Empty, a % 5 == 0 ? "Buzz" : string.Empty)) .Select((b, i) => String.IsNullOrEmpty(b) ? (i + 1).ToString() : b) .ToList() .ForEach(Console.WriteLine); } }
}</lang> <lang csharp>using System; using System.Globalization; using System.Linq;
namespace FizzBuzz {
class Program { static void Main() { Enumerable.Range(1, 100) .GroupBy(e => e % 15 == 0 ? "FizzBuzz" : e % 5 == 0 ? "Buzz" : e % 3 == 0 ? "Fizz" : string.Empty) .SelectMany(item => item.Select(x => new { Value = x, Display = String.IsNullOrEmpty(item.Key) ? x.ToString(CultureInfo.InvariantCulture) : item.Key })) .OrderBy(x => x.Value) .Select(x => x.Display) .ToList() .ForEach(Console.WriteLine); } }
}</lang>
<lang csharp>using System;
namespace FizzBuzz {
class Program { static void Main(string[] args) { for (int i = 1; i <= 100; i++) { if (i % 15 == 0) { Console.WriteLine("FizzBuzz"); } else if (i % 3 == 0) { Console.WriteLine("Fizz"); } else if (i % 5 == 0) { Console.WriteLine("Buzz"); } else { Console.WriteLine(i); } } } }
}</lang>
<lang csharp>using System; using System.Globalization;
namespace Rosettacode {
class Program { static void Main() { for (var number = 0; number < 100; number++) { if ((number % 3) == 0 & (number % 5) == 0) { //For numbers which are multiples of both three and five print "FizzBuzz". Console.WriteLine("FizzBuzz"); continue; }
if ((number % 3) == 0) Console.WriteLine("Fizz"); if ((number % 5) == 0) Console.WriteLine("Buzz"); if ((number % 3) != 0 && (number % 5) != 0) Console.WriteLine(number.ToString(CultureInfo.InvariantCulture));
if (number % 5 == 0) { Console.WriteLine(Environment.NewLine); } } } }
}</lang> TDD using delegates. <lang csharp>using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FizzBuzz {
[TestClass] public class FizzBuzzTest { private FizzBuzz fizzBuzzer;
[TestInitialize] public void Initialize() { fizzBuzzer = new FizzBuzz(); }
[TestMethod] public void Give4WillReturn4() { Assert.AreEqual("4", fizzBuzzer.FizzBuzzer(4)); }
[TestMethod] public void Give9WillReturnFizz() { Assert.AreEqual("Fizz", fizzBuzzer.FizzBuzzer(9)); }
[TestMethod] public void Give25WillReturnBuzz() { Assert.AreEqual("Buzz", fizzBuzzer.FizzBuzzer(25)); }
[TestMethod] public void Give30WillReturnFizzBuzz() { Assert.AreEqual("FizzBuzz", fizzBuzzer.FizzBuzzer(30)); }
[TestMethod] public void First15() { ICollection expected = new ArrayList {"1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"};
var actual = Enumerable.Range(1, 15).Select(x => fizzBuzzer.FizzBuzzer(x)).ToList();
CollectionAssert.AreEqual(expected, actual); }
[TestMethod] public void From1To100_ToShowHowToGet100() { const int expected = 100; var actual = Enumerable.Range(1, 100).Select(x => fizzBuzzer.FizzBuzzer(x)).ToList();
Assert.AreEqual(expected, actual.Count); } }
public class FizzBuzz { private delegate string Xzzer(int value); private readonly IList<Xzzer> _functions = new List<Xzzer>();
public FizzBuzz() { _functions.Add(x => x % 3 == 0 ? "Fizz" : ""); _functions.Add(x => x % 5 == 0 ? "Buzz" : ""); }
public string FizzBuzzer(int value) { var result = _functions.Aggregate(String.Empty, (current, function) => current + function.Invoke(value)); return String.IsNullOrEmpty(result) ? value.ToString(CultureInfo.InvariantCulture) : result; } }
}</lang>
Casio BASIC
See FizzBuzz/Basic
Cduce
<lang ocaml>(* FizzBuzz in CDuce *)
let format (n : Int) : Latin1 =
if (n mod 3 = 0) || (n mod 5 = 0) then "FizzBuzz" else if (n mod 5 = 0) then "Buzz" else if (n mod 3 = 0) then "Fizz" else string_of (n);;
let fizz (n : Int, size : Int) : _ =
print (format (n) @ "\n"); if (n = size) then n = 0 (* do nothing *) else fizz(n + 1, size);;
let fizbuzz (size : Int) : _ = fizz (1, size);;
let _ = fizbuzz(100);;</lang>
Ceylon
<lang Ceylon>shared void run() => {for (i in 1..100) {for (j->k in [3->"Fizz", 5->"Buzz"]) if (j.divides(i)) k}.reduce(plus) else i}.each(print);</lang>
Chef
See FizzBuzz/EsoLang
Clay
<lang clay>main() {
for(i in range(1,100)) { if(i % 3 == 0 and i % 5 == 0) println("fizzbuzz"); else if(i % 3 == 0) println("fizz"); else if(i % 5 == 0) println("buzz"); else print(i); }
}</lang>
Clipper
Also compiles with Harbour (Harbour 3.2.0dev (r1405201749)) <lang Clipper>PROCEDURE Main()
LOCAL n LOCAL cFB
FOR n := 1 TO 100 cFB := "" AEval( { { 3, "Fizz" }, { 5, "Buzz" } }, {|x| cFB += iif( ( n % x[ 1 ] ) == 0, x[ 2 ], "" ) } ) ?? iif( cFB == "", LTrim( Str( n ) ), cFB ) + iif( n == 100, ".", ", " ) NEXT
RETURN
</lang> The advantage of this approach is that it is trivial to add another factor:
AEval( {{3,"Fizz"},{5,"Buzz"},{9,"Jazz"}}, {|x| cFB += Iif((n % x[1])==0, x[2], "")})
CLIPS
<lang clips>(deffacts count
(count-to 100)
)
(defrule print-numbers
(count-to ?max) => (loop-for-count (?num ?max) do (if (= (mod ?num 3) 0) then (printout t "Fizz") ) (if (= (mod ?num 5) 0) then (printout t "Buzz") ) (if (and (> (mod ?num 3) 0) (> (mod ?num 5) 0)) then (printout t ?num) ) (priint depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_COREntout t crlf) )
)</lang>
Clojure
<lang clojure> (defn fizzbuzz [start finish]
(map (fn [n]
(cond (zero? (mod n 15)) "FizzBuzz" (zero? (mod n 3)) "Fizz" (zero? (mod n 5)) "Buzz" :else n)) (range start finish))) (fizzbuzz 1 100) </lang>
<lang lisp>(map (fn [x] (cond (zero? (mod x 15)) "FizzBuzz"
(zero? (mod x 5)) "Buzz" (zero? (mod x 3)) "Fizz"
:else x))
(range 1 101))</lang>
<lang lisp>(map #(let [s (str (if (zero? (mod % 3)) "Fizz") (if (zero? (mod % 5)) "Buzz"))] (if (empty? s) % s)) (range 1 101))</lang> <lang lisp>(def fizzbuzz (map
#(cond (zero? (mod % 15)) "FizzBuzz" (zero? (mod % 5)) "Buzz" (zero? (mod % 3)) "Fizz" :else %) (iterate inc 1)))</lang>
<lang lisp>(defn fizz-buzz
([] (fizz-buzz (range 1 101))) ([lst] (letfn [(fizz? [n] (zero? (mod n 3)))
(buzz? [n] (zero? (mod n 5)))]
(let [f "Fizz"
b "Buzz" items (map (fn [n] (cond (and (fizz? n) (buzz? n)) (str f b) (fizz? n) f (buzz? n) b :else n)) lst)] items))))</lang> <lang clojure>(map (fn [n]
(if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz") (when (zero? (mod n 5)) "Buzz")))] (apply str fb) n)) (range 1 101))</lang>
<lang clojure>(take 100 (map #(let [s (str %2 %3) ] (if (seq s) s (inc %)) )
(range) (cycle [ "" "" "Fizz" ]) (cycle [ "" "" "" "" "Buzz" ])))</lang>
<lang lisp>(map #(nth (conj (cycle [% % "Fizz" % "Buzz" "Fizz" % % "Fizz" "Buzz" % "Fizz" % % "FizzBuzz"]) %) %) (range 1 101))</lang> <lang clojure>(let [n nil fizz (cycle [n n "fizz"]) buzz (cycle [n n n n "buzz"]) nums (iterate inc 1)]
(take 20 (map #(if (or %1 %2) (str %1 %2) %3) fizz buzz nums)))</lang>
<lang clojure>(take 100
(map #(if (pos? (compare %1 %2)) %1 %2) (map str (drop 1 (range))) (map str (cycle ["" "" "Fizz"]) (cycle ["" "" "" "" "Buzz"]))))
</lang> <lang clojure>
- Using clojure maps
(defn fizzbuzz
[n] (let [rule {3 "Fizz" 5 "Buzz"} divs (->> rule (map first) sort (filter (comp (partial = 0) (partial rem n))))] (if (empty? divs) (str n) (->> divs (map rule) (apply str)))))
(defn allfizzbuzz
[max] (map fizzbuzz (range 1 (inc max))))
</lang>
CMake
<lang cmake>foreach(i RANGE 1 100)
math(EXPR off3 "${i} % 3") math(EXPR off5 "${i} % 5") if(NOT off3 AND NOT off5) message(FizzBuzz) elseif(NOT off3) message(Fizz) elseif(NOT off5) message(Buzz) else() message(${i}) endif()
endforeach(i)</lang>
COBOL
Canonical version
<lang COBOL> * FIZZBUZZ.COB
* cobc -x -g FIZZBUZZ.COB * IDENTIFICATION DIVISION. PROGRAM-ID. fizzbuzz. DATA DIVISION. WORKING-STORAGE SECTION. 01 CNT PIC 9(03) VALUE 1. 01 REM PIC 9(03) VALUE 0. 01 QUOTIENT PIC 9(03) VALUE 0. PROCEDURE DIVISION. * PERFORM UNTIL CNT > 100 DIVIDE 15 INTO CNT GIVING QUOTIENT REMAINDER REM IF REM = 0 THEN DISPLAY "FizzBuzz " WITH NO ADVANCING ELSE DIVIDE 3 INTO CNT GIVING QUOTIENT REMAINDER REM IF REM = 0 THEN DISPLAY "Fizz " WITH NO ADVANCING ELSE DIVIDE 5 INTO CNT GIVING QUOTIENT REMAINDER REM IF REM = 0 THEN DISPLAY "Buzz " WITH NO ADVANCING ELSE DISPLAY CNT " " WITH NO ADVANCING END-IF END-IF END-IF ADD 1 TO CNT END-PERFORM DISPLAY "" STOP RUN.</lang>
Simpler version
I know this doesn't have the full-bodied, piquant flavor expected from COBOL, but it is a little shorter.
<lang cobol>Identification division. Program-id. fizz-buzz.
Data division. Working-storage section.
01 num pic 999.
Procedure division.
Perform varying num from 1 by 1 until num > 100 if function mod (num, 15) = 0 then display "fizzbuzz" else if function mod (num, 3) = 0 then display "fizz" else if function mod (num, 5) = 0 then display "buzz" else display num end-perform. Stop run.</lang>
Evaluate Version
I think this shows clearly that it's resolving the problem and illuminating the rules specified
<lang cobol>
IDENTIFICATION DIVISION. PROGRAM-ID. FIZZBUZZ. ENVIRONMENT DIVISION. DATA DIVISION. WORKING-STORAGE SECTION. 01 X PIC 999. 01 Y PIC 999. 01 REM3 PIC 999. 01 REM5 PIC 999. PROCEDURE DIVISION. PERFORM VARYING X FROM 1 BY 1 UNTIL X > 100 DIVIDE X BY 3 GIVING Y REMAINDER REM3 DIVIDE X BY 5 GIVING Y REMAINDER REM5 EVALUATE REM3 ALSO REM5 WHEN ZERO ALSO ZERO DISPLAY "FizzBuzz" WHEN ZERO ALSO ANY DISPLAY "Fizz" WHEN ANY ALSO ZERO DISPLAY "Buzz" WHEN OTHER DISPLAY X END-EVALUATE END-PERFORM STOP RUN .
</lang>
Coco
<lang coco>for i from 1 to 100
console.log do if i % 15 == 0 then 'FizzBuzz' else if i % 3 == 0 then 'Fizz' else if i % 5 == 0 then 'Buzz' else i</lang>
<lang coco>for i from 1 to 100
console.log(['Fizz' unless i % 3] + ['Buzz' unless i % 5] or String(i))</lang>
CoffeeScript
<lang CoffeeScript>for i in [1..100]
if i % 15 is 0 console.log "FizzBuzz" else if i % 3 is 0 console.log "Fizz" else if i % 5 is 0 console.log "Buzz" else console.log i</lang>
<lang CoffeeScript>for i in [1..100]
console.log \ if i % 15 is 0 "FizzBuzz" else if i % 3 is 0 "Fizz" else if i % 5 is 0 "Buzz" else i</lang>
<lang CoffeeScript>for i in [1..100]
console.log(['Fizz' if i % 3 is 0] + ['Buzz' if i % 5 is 0] or i)</lang>
ColdFusion
<lang cfm> <Cfloop from="1" to="100" index="i">
<Cfif i mod 15 eq 0>FizzBuzz <Cfelseif i mod 5 eq 0>Fizz <Cfelseif i mod 3 eq 0>Buzz <Cfelse><Cfoutput>#i#</Cfoutput> </Cfif>
</Cfloop> </lang>
Common Lisp
Solution 1: <lang lisp>(defun fizzbuzz ()
(loop for x from 1 to 100 do (princ (cond ((zerop (mod x 15)) "FizzBuzz") ((zerop (mod x 3)) "Fizz") ((zerop (mod x 5)) "Buzz") (t x))) (terpri)))</lang>
Solution 2: <lang lisp>(defun fizzbuzz ()
(loop for x from 1 to 100 do (format t "~&~{~A~}" (or (append (when (zerop (mod x 3)) '("Fizz")) (when (zerop (mod x 5)) '("Buzz"))) (list x)))))</lang>
Solution 3: <lang lisp>(defun fizzbuzz ()
(loop for n from 1 to 100 do (format t "~&~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%" (mod n 3) (mod n 5) n)))</lang>
Solution 4: <lang lisp>(loop as n from 1 to 100
as fizz = (zerop (mod n 3)) as buzz = (zerop (mod n 5)) as numb = (not (or fizz buzz)) do (format t "~&~:[~;Fizz~]~:[~;Buzz~]~:[~;~D~]~%" fizz buzz numb n))</lang>
Solution 5: <lang lisp>(format t "~{~:[~&~;~:*~:(~a~)~]~}"
(loop as n from 1 to 100 as f = (zerop (mod n 3)) as b = (zerop (mod n 5)) collect nil if f collect 'fizz if b collect 'buzz if (not (or f b)) collect n))</lang>
Solution 6: <lang lisp>(format t "~{~{~:[~;Fizz~]~:[~;Buzz~]~:[~*~;~d~]~}~%~}"
(loop as n from 1 to 100 as f = (zerop (mod n 3)) as b = (zerop (mod n 5)) collect (list f b (not (or f b)) n)))</lang>
First 16 lines of output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16
Crystal
<lang ruby>1.upto(100) do |v|
p fizz_buzz(v)
end
def fizz_buzz(value)
word = "" word += "fizz" if value % 3 == 0 word += "buzz" if value % 5 == 0 word += value.to_s if word.empty? word
end</lang>
Cubescript
<lang>alias fizzbuzz [ loop i 100 [ push i (+ $i 1) [ cond (! (mod $i 15)) [ echo FizzBuzz ] (! (mod $i 3)) [ echo Fizz ] (! (mod $i 5)) [ echo Buzz ] [ echo $i ] ] ] ]</lang>
Chapel
<lang chapel>proc fizzbuzz(n) { for i in 1..n do if i % 15 == 0 then writeln("FizzBuzz"); else if i % 5 == 0 then writeln("Buzz"); else if i % 3 == 0 then writeln("Fizz"); else writeln(i); }
fizzbuzz(100);</lang>
D
<lang d>import std.stdio, std.algorithm, std.conv;
/// With if-else. void fizzBuzz(in uint n) {
foreach (immutable i; 1 .. n + 1) if (!(i % 15)) "FizzBuzz".writeln; else if (!(i % 3)) "Fizz".writeln; else if (!(i % 5)) "Buzz".writeln; else i.writeln;
}
/// With switch case. void fizzBuzzSwitch(in uint n) {
foreach (immutable i; 1 .. n + 1) switch (i % 15) { case 0: "FizzBuzz".writeln; break; case 3, 6, 9, 12: "Fizz".writeln; break; case 5, 10: "Buzz".writeln; break; default: i.writeln; }
}
void fizzBuzzSwitch2(in uint n) {
foreach (immutable i; 1 .. n + 1) (i % 15).predSwitch( 0, "FizzBuzz", 3, "Fizz", 5, "Buzz", 6, "Fizz", 9, "Fizz", 10, "Buzz", 12, "Fizz", /*else*/ i.text).writeln;
}
void main() {
100.fizzBuzz; writeln; 100.fizzBuzzSwitch; writeln; 100.fizzBuzzSwitch2;
}</lang>
Dart
<lang dart>main() {
for (int i = 1; i <= 100; i++) { print((i % 3 == 0 ? "Fizz" : "") + (i % 5 == 0 ? "Buzz" : "") + (i % 3 != 0 && i % 5 != 0 ? "$i" : "")); }
}</lang>
dc
<lang dc>[[Fizz]P 1 sw]sF [[Buzz]P 1 sw]sB [li p sz]sN [[ ]P]sW [
0 sw [w = 0]sz li 3 % 0 =F [Fizz if 0 == i % 3]sz li 5 % 0 =B [Buzz if 0 == i % 5]sz lw 0 =N [print Number if 0 == w]sz lw 1 =W [print neWline if 1 == w]sz li 1 + si [i += 1]sz li 100 !<L [continue Loop if 100 >= i]sz
]sL 1 si [i = 1]sz 0 0 =L [enter Loop]sz</lang> The bc translation written in dc style. <lang dc>
- dc is stack based, so we use the stack instead of a variable for our
- current number.
1 # Number = 1 [[Fizz]n 1 sw]sF # Prints "Fizz" prevents Number from printing [[Buzz]n 1 sw]sB # Prints "Buzz" prevents Number from printing [dn]sN # Prints Number [
dd # Put two extra copies of Number on stack 0 sw # w = 0 3% 0=F # Fizz if 0 == Number % 3 (destroys 1st copy) 5% 0=B # Buzz if 0 == Number % 5 (destroys 2nd copy) lw 0=N # Print Number if 0 == w [
]n # Print new line
1+d # Number += 1 and put extra copy on stack 100!<L # Continue Loop if 100 >= Number (destroys copy)
]dsLx # Enter Loop</lang>
Delphi
<lang Delphi>program FizzBuzz;
{$APPTYPE CONSOLE}
uses SysUtils;
var
i: Integer;
begin
for i := 1 to 100 do begin if i mod 15 = 0 then Writeln('FizzBuzz') else if i mod 3 = 0 then Writeln('Fizz') else if i mod 5 = 0 then Writeln('Buzz') else Writeln(i); end;
end.</lang>
Déjà Vu
<lang dejavu>for i range 1 100: if = 0 % i 15: "FizzBuzz" elseif = 0 % i 3: "Fizz" elseif = 0 % i 5: "Buzz" else: i !print</lang>
DeviousYarn
<lang deviousyarn>each { x range(1 100)
? { divisible(x 3) p:'Fizz' } ? { divisible(x 5) p:'Buzz' } -? { !:divisible(x 3) p:x } o
}</lang>
DWScript
<lang delphi>var i : Integer;
for i := 1 to 100 do begin
if i mod 15 = 0 then PrintLn('FizzBuzz') else if i mod 3 = 0 then PrintLn('Fizz') else if i mod 5 = 0 then PrintLn('Buzz') else PrintLn(i);
end;</lang>
E
<lang e>for i in 1..100 {
println(switch ([i % 3, i % 5]) { match [==0, ==0] { "FizzBuzz" } match [==0, _ ] { "Fizz" } match [_, ==0] { "Buzz" } match _ { i } }) }</lang>
Eiffel
<lang Eiffel> class APPLICATION
create make
feature
make do fizzbuzz end
fizzbuzz --Numbers up to 100, prints "Fizz" instead of multiples of 3, and "Buzz" for multiples of 5. --For multiples of both 3 and 5 prints "FizzBuzz". do across 1 |..| 100 as c loop if c.item \\ 15 = 0 then io.put_string ("FIZZBUZZ%N") elseif c.item \\ 3 = 0 then io.put_string ("FIZZ%N") elseif c.item \\ 5 = 0 then io.put_string ("BUZZ%N") else io.put_string (c.item.out + "%N") end end end
end
</lang>
ECL
<lang ECL>DataRec := RECORD
STRING s;
END;
DataRec MakeDataRec(UNSIGNED c) := TRANSFORM
SELF.s := MAP ( c % 15 = 0 => 'FizzBuzz', c % 3 = 0 => 'Fizz', c % 5 = 0 => 'Buzz', (STRING)c );
END;
d := DATASET(100,MakeDataRec(COUNTER));
OUTPUT(d);</lang>
Eero
<lang objc>#import <Foundation/Foundation.h>
int main()
autoreleasepool
for int i in 1 .. 100 s := if i % 3 == 0 s << 'Fizz' if i % 5 == 0 s << 'Buzz' Log( '(%d) %@', i, s )
return 0</lang>
Ela
<lang ela>open list
prt x | x % 15 == 0 = "FizzBuzz"
| x % 3 == 0 = "Fizz" | x % 5 == 0 = "Buzz" | else = x
[1..100] |> map prt</lang>
Elixir
Standard approaches
<lang elixir>Enum.each 1..100, fn x ->
IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do { true, true } -> "FizzBuzz" { true, false } -> "Fizz" { false, true } -> "Buzz" { false, false } -> x end)
end</lang>
Alternate approach using pipes and con:
<lang elixir>#!/usr/bin/env elixir 1..100 |> Enum.map(fn i ->
cond do rem(i,3*5) == 0 -> "fizzbuzz" rem(i,3) == 0 -> "fizz" rem(i,5) == 0 -> "buzz" true -> i end
end) |> Enum.each(fn i -> IO.puts i end)</lang>
used Stream.cycle version: <lang elixir>defmodule RC do
def fizzbuzz(limit \\ 100) do fizz = Stream.cycle(["", "", "Fizz"]) buzz = Stream.cycle(["", "", "", "", "Buzz"]) Stream.zip(fizz, buzz) |> Stream.with_index |> Enum.take(limit) |> Enum.each(fn {{f,b},i} -> IO.puts if f<>b=="", do: i+1, else: f<>b end) end
end
RC.fizzbuzz</lang>
Yet another approach: <lang elixir>defmodule FizzBuzz do
def fizzbuzz(n) when rem(n, 15) == 0, do: "FizzBuzz" def fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz" def fizzbuzz(n) when rem(n, 3) == 0, do: "Fizz" def fizzbuzz(n), do: n
end
Enum.map(1..100, &FizzBuzz.fizzbuzz/1)</lang>
A macro too far
The Stream.cycle version above, but as an overpowered FizzBuzz DSL. <lang elixir>defmodule BadFizz do
# Hand-rolls a bunch of AST before injecting the resulting FizzBuzz code. defmacrop automate_fizz(fizzers, n) do # To begin, we need to process fizzers to produce the various components # we're using in the final assembly. As told by Mickens telling as Antonio # Banderas, first you must specify a mapping function: build_parts = (fn {fz, n} -> ast_ref = {fz |> String.downcase |> String.to_atom, [], __MODULE__} clist = List.duplicate("", n - 1) ++ [fz] cycle = quote do: unquote(ast_ref) = unquote(clist) |> Stream.cycle
{ast_ref, cycle} end)
# ...and then a reducing function: collate = (fn ({ast_ref, cycle}, {ast_refs, cycles}) -> {[ast_ref | ast_refs], [cycle | cycles]} end)
# ...and then, my love, when you are done your computation is ready to run # across thousands of fizzbuzz: {ast_refs, cycles} = fizzers |> Code.eval_quoted([], __ENV__) |> elem(0) # Gotta unwrap this mystery code~ |> Enum.sort(fn ({_, ap}, {_, bp}) -> ap < bp end) # Sort so that Fizz, 3 < Buzz, 5 |> Enum.map(build_parts) |> Enum.reduce({[], []}, collate)
# Setup the anonymous functions used by Enum.reduce to build our AST components. # This was previously handled by List.foldl, but ejected because reduce/2's # default behavior reduces repetition. # # ...I was tempted to move these into a macro themselves, and thought better of it. build_zip = fn (varname, ast) -> quote do: Stream.zip(unquote(varname), unquote(ast)) end build_tuple = fn (varname, ast) -> {:{}, [], [varname, ast]} end build_concat = fn (varname, ast) -> {:<>, [context: __MODULE__, import: Kernel], # Hygiene values may change; accurate to Elixir 1.1.1 [varname, ast]} end
# Toss cycles into a block by hand, then smash ast_refs into # a few different computations on the cycle block results. cycles = {:__block__, [], cycles} tuple = ast_refs |> Enum.reduce(build_tuple) zip = ast_refs |> Enum.reduce(build_zip) concat = ast_refs |> Enum.reduce(build_concat)
# Finally-- Now that all our components are assembled, we can put # together the fizzbuzz stream pipeline. After quote ends, this # block is injected into the caller's context. quote do unquote(cycles)
unquote(zip) |> Stream.with_index |> Enum.take(unquote(n)) |> Enum.each(fn {unquote(tuple), i} -> ccats = unquote(concat) IO.puts if ccats == "", do: i + 1, else: ccats end) end end
@doc ~S""" A fizzing, and possibly buzzing function. Somehow, you feel like you've seen this before. An old friend, suddenly appearing in Kafkaesque nightmare...
...or worse, during a whiteboard interview. """ def fizz(n \\ 100) when is_number(n) do # In reward for all that effort above, we now have the latest in # programmer productivity: # # A DSL for building arbitrary fizzing, buzzing, bazzing, and more! [{"Fizz", 3}, {"Buzz", 5}#, #{"Bar", 7}, #{"Foo", 243}, # -> Always printed last (largest number) #{"Qux", 34} ] |> automate_fizz(n) end
end
BadFizz.fizz(100) # => Prints to stdout</lang>
Elm
A bit too simple: <lang elm>import Graphics.Element exposing (show) import List exposing (map)
main =
map getWordForNum [1..100] |> show
getWordForNum num =
if num % 15 == 0 then "FizzBuzz" else if num % 3 == 0 then "Fizz" else if num % 5 == 0 then "Buzz" else toString num</lang>
A bit too clever: <lang elm>import Html exposing (text) import List exposing (map) import String exposing (join)
main : Html.Html main =
map fizzbuzz [1..100] |> join " " |> text
fizzbuzz : Int -> String fizzbuzz num =
let fizz = if num % 3 == 0 then "Fizz" else "" buzz = if num % 5 == 0 then "Buzz" else "" in if fizz == buzz then toString num else fizz ++ buzz</lang>
Erlang
<lang erlang>fizzbuzz() ->
F = fun(N) when N rem 15 == 0 -> "FizzBuzz"; (N) when N rem 3 == 0 -> "Fizz"; (N) when N rem 5 == 0 -> "Buzz"; (N) -> integer_to_list(N) end, [F(N)++"\n" || N <- lists:seq(1,100)].</lang>
ERRE
<lang ERRE> PROGRAM FIZZ_BUZZ ! ! for rosettacode.org ! BEGIN
FOR A=1 TO 100 DO IF A MOD 15=0 THEN PRINT("FizzBuzz") ELSIF A MOD 3=0 THEN PRINT("Fizz") ELSIF A MOD 5=0 THEN PRINT("Buzz") ELSE PRINT(A) END IF END FOR
END PROGRAM </lang>
Euphoria
This is based on the VBScript example. <lang Euphoria>include std/utils.e
function fb( atom n ) sequence fb if remainder( n, 15 ) = 0 then fb = "FizzBuzz" elsif remainder( n, 5 ) = 0 then fb = "Fizz" elsif remainder( n, 3 ) = 0 then fb = "Buzz" else fb = sprintf( "%d", n ) end if return fb end function
function fb2( atom n ) return iif( remainder(n, 15) = 0, "FizzBuzz", iif( remainder( n, 5 ) = 0, "Fizz", iif( remainder( n, 3) = 0, "Buzz", sprintf( "%d", n ) ) ) ) end function
for i = 1 to 30 do printf( 1, "%s ", { fb( i ) } ) end for
puts( 1, "\n" )
for i = 1 to 30 do printf( 1, "%s ", { fb2( i ) } ) end for
puts( 1, "\n" )</lang>
Factor
<lang factor>USING: math kernel io math.ranges ; IN: fizzbuzz
- fizz ( n -- str ) 3 divisor? "Fizz" "" ? ;
- buzz ( n -- str ) 5 divisor? "Buzz" "" ? ;
- fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ;
- main ( -- ) 100 [1,b] [ fizzbuzz print ] each ;
MAIN: main</lang>
F#
<lang fsharp>let fizzbuzz n =
match n%3 = 0, n%5 = 0 with | true, false -> "fizz" | false, true -> "buzz" | true, true -> "fizzbuzz" | _ -> string n
let printFizzbuzz() =
[1..100] |> List.iter (fizzbuzz >> printfn "%s")</lang>
<lang fsharp>[1..100] |> List.map (fun x ->
match x with | _ when x % 15 = 0 ->"fizzbuzz" | _ when x % 5 = 0 -> "buzz" | _ when x % 3 = 0 -> "fizz" | _ -> x.ToString())
|> List.iter (fun x -> printfn "%s" x) </lang> Another example using (unnecessary) partial active pattern :D <lang fsharp>let (|MultipleOf|_|) divisors number =
if Seq.exists ((%) number >> (<>) 0) divisors then None else Some ()
let fizzbuzz = function | MultipleOf [3; 5] -> "fizzbuzz" | MultipleOf [3] -> "fizz" | MultipleOf [5] -> "buzz" | n -> string n
{ 1 .. 100 } |> Seq.iter (fizzbuzz >> printfn "%s")</lang>
Falcon
<lang falcon>for i in [1:101]
switch i % 15 case 0 : > "FizzBuzz" case 5,10 : > "Buzz" case 3,6,9,12 : > "Fizz" default : > i end
end</lang>
FALSE
See FizzBuzz/EsoLang
Fantom
<lang fantom>class FizzBuzz {
public static Void main () { for (Int i:=1; i <= 100; ++i) { if (i % 15 == 0) echo ("FizzBuzz") else if (i % 3 == 0) echo ("Fizz") else if (i % 5 == 0) echo ("Buzz") else echo (i) } }
}</lang>
FBSL
No 'MOD 15' needed. <lang qbasic>#APPTYPE CONSOLE
DIM numbers AS STRING DIM imod5 AS INTEGER DIM imod3 AS INTEGER
FOR DIM i = 1 TO 100
numbers = "" imod3 = i MOD 3 imod5 = i MOD 5 IF NOT imod3 THEN numbers = "Fizz" IF NOT imod5 THEN numbers = numbers & "Buzz" IF imod3 AND imod5 THEN numbers = i PRINT numbers, " ";
NEXT
PAUSE</lang>
- Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fiz z 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 Fi zzBuzz 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 Press any key to continue...
Forth
table-driven
<lang forth>: fizz ( n -- ) drop ." Fizz" ;
- buzz ( n -- ) drop ." Buzz" ;
- fb ( n -- ) drop ." FizzBuzz" ;
- vector create does> ( n -- )
over 15 mod cells + @ execute ;
vector .fizzbuzz
' fb , ' . , ' . , ' fizz , ' . , ' buzz , ' fizz , ' . , ' . , ' fizz , ' buzz , ' . , ' fizz , ' . , ' . ,</lang>
or the classic approach
<lang forth>: .fizzbuzz ( n -- )
0 pad c! dup 3 mod 0= if s" Fizz" pad place then dup 5 mod 0= if s" Buzz" pad +place then pad c@ if drop pad count type else . then ;
- zz ( n -- )
1+ 1 do i .fizzbuzz cr loop ;
100 zz</lang>
the well factored approach
SYNONYM is a Forth200x word.
<lang forth>SYNONYM NOT INVERT \ Bitwise boolean not
- Fizz? ( n -- ? ) 3 MOD 0= DUP IF ." Fizz" THEN ;
- Buzz? ( n -- ? ) 5 MOD 0= DUP IF ." Buzz" THEN ;
- ?print ( n ? -- ) IF . THEN ;
- FizzBuzz ( -- )
101 1 DO CR I DUP Fizz? OVER Buzz? OR NOT ?print LOOP ;
FizzBuzz</lang>
Fortran
In ANSI FORTRAN 77 or later use structured IF-THEN-ELSE (example uses some ISO Fortran 90 features): <lang fortran>program fizzbuzz_if
integer :: i do i = 1, 100 if (mod(i,15) == 0) then; print *, 'FizzBuzz' else if (mod(i,3) == 0) then; print *, 'Fizz' else if (mod(i,5) == 0) then; print *, 'Buzz' else; print *, i end if end do
end program fizzbuzz_if</lang> This example uses If statements to print "Fizz" and "Buzz" next to each other if the number is divisible by 3 and 5 by waiting to use a line break until after the If statements. <lang fortran>program FizzBuzz implicit none integer :: i = 1
do i = 1, 100
if (Mod(i,3) == 0)write(*,"(A)",advance='no') "Fizz" if (Mod(i,5) == 0)write(*,"(A)",advance='no') "Buzz" if (Mod(i,3) /= 0 .and. Mod(i,5) /=0 )write(*,"(I3)",advance='no') i print *, ""
end do end program FizzBuzz </lang> In ISO Fortran 90 or later use SELECT-CASE statement: <lang fortran>program fizzbuzz_select
integer :: i do i = 1, 100 select case (mod(i,15)) case 0; print *, 'FizzBuzz' case 3,6,9,12; print *, 'Fizz' case 5,10; print *, 'Buzz' case default; print *, i end select end do end program fizzbuzz_select</lang>
Frege
<lang Frege>gen n word = cycle (take (n - 1) (repeat "") ++ [word]) pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz") fizzbuzz = zipWith combine pattern [1..] where
combine word number = if null word then show number else word
show $ take 100 fizzbuzz</lang>
Frink
<lang frink>for i = 1 to 100 {
flag = false if i mod 3 == 0 { flag = true print["Fizz"] } if i mod 5 == 0 { flag = true print["Buzz"] }
if flag == false print[i]
println[]
}</lang>
FutureBasic
<lang futurebasic> include "ConsoleWindow"
dim as short fizz, buzz, i dim as Str15 s
for i = 1 to 100
fizz = (i mod 3 ) buzz = (i mod 5 ) if (i) if fizz + buzz == 0 then print i; ".", "FizzBuzz" : exit if if fizz == 0 then print i; ".", "Fizz" : exit if if buzz == 0 then print i; ".", "Buzz" : exit if print i end if
next i
</lang>
Output:
1 2 3. Fizz 4 5. Buzz 6. Fizz 7 8 9. Fizz 10. Buzz 11 12. Fizz 13 14 15. FizzBuzz 16 17 18. Fizz 19 20. Buzz 21. Fizz 22 23 24. Fizz 25. Buzz 26 27. Fizz 28 29 30. FizzBuzz 31 32 33. Fizz 34 35. Buzz 36. Fizz 37 38 39. Fizz 40. Buzz 41 42. Fizz 43 44 45. FizzBuzz 46 47 48. Fizz 49 50. Buzz 51. Fizz 52 53 54. Fizz 55. Buzz 56 57. Fizz 58 59 60. FizzBuzz 61 62 63. Fizz 64 65. Buzz 66. Fizz 67 68 69. Fizz 70. Buzz 71 72. Fizz 73 74 75. FizzBuzz 76 77 78. Fizz 79 80. Buzz 81. Fizz 82 83 84. Fizz 85. Buzz 86 87. Fizz 88 89 90. FizzBuzz 91 92 93. Fizz 94 95. Buzz 96. Fizz 97 98 99. Fizz 100. Buzz
GAP
<lang gap>FizzBuzz := function() local i; for i in [1 .. 100] do if RemInt(i, 15) = 0 then Print("FizzBuzz\n"); elif RemInt(i, 3) = 0 then Print("Fizz\n"); elif RemInt(i, 5) = 0 then Print("Buzz\n"); else Print(i, "\n"); fi; od; end;</lang>
GFA Basic
<lang> ' Fizz Buzz ' FOR i%=1 TO 100
IF i% MOD 15=0 PRINT "FizzBuzz" ELSE IF i% MOD 3=0 PRINT "Fizz" ELSE IF i% MOD 5=0 PRINT "Buzz" ELSE PRINT i% ENDIF
NEXT i% </lang>
Go
<lang go>package main
import "fmt"
func main() {
for i := 1; i <= 100; i++ { switch { case i%15==0: fmt.Println("FizzBuzz") case i%3==0: fmt.Println("Fizz") case i%5==0: fmt.Println("Buzz") default: fmt.Println(i) } }
}</lang>
Gosu
<lang gosu>for (i in 1..100) {
if (i % 3 == 0 && i % 5 == 0) { print("FizzBuzz") continue } if (i % 3 == 0) { print("Fizz") continue } if (i % 5 == 0) { print("Buzz") continue } // default print(i)
}</lang> One liner version (I added new lines to better readability but when you omit them it's one liner): <lang gosu>// note that compiler reports error (I don't know why) but still it's working for (i in 1..100) {
print(i % 5 == 0 ? i % 3 == 0 ? "FizzBuzz" : "Buzz" : i % 3 == 0 ? "Fizz" : i)
}</lang>
Groovy
<lang groovy>for (i in 1..100) {
println "${i%3?:'Fizz'}${i%5?:'Buzz'}" ?: i
}</lang>
GW-BASIC
See FizzBuzz/Basic
Haskell
Variant directly implementing the specification: <lang haskell>main = mapM_ (putStrLn . fizzbuzz) [1..100]
fizzbuzz x
| x `mod` 15 == 0 = "FizzBuzz" | x `mod` 3 == 0 = "Fizz" | x `mod` 5 == 0 = "Buzz" | otherwise = show x</lang>
<lang haskell>main = putStr $ concat $ map fizzbuzz [1..100]
fizzbuzz n =
"\n" ++ if null (fizz++buzz) then show n else fizz++buzz where fizz = if mod n 3 == 0 then "Fizz" else "" buzz = if mod n 5 == 0 then "Buzz" else ""</lang>
Does not perform the mod 15 step, extesible to arbitrary addtional tests, ex: [bar| n `mod` 7 == 0]. <lang haskell>main = mapM_ (putStrLn . fizzbuzz) [1..100]
fizzbuzz n =
show n <|> [fizz| n `mod` 3 == 0] ++ [buzz| n `mod` 5 == 0]
-- A simple default choice operator. -- Defaults if both fizz and buzz fail, concats if any succeed. infixr 0 <|> d <|> [] = d _ <|> x = concat x
fizz = "Fizz" buzz = "Buzz"</lang> Alternate implementation using lazy infinite lists and avoiding use of "mod": <lang haskell>main = mapM_ putStrLn $ take 100 $ zipWith show_number_or_fizzbuzz [1..] fizz_buzz_list
show_number_or_fizzbuzz x y = if null y then show x else y
fizz_buzz_list = zipWith (++) (cycle ["","","Fizz"]) (cycle ["","","","","Buzz"])</lang> Using heavy artillery (needs the mtl package): <lang haskell> import Control.Monad.State import Control.Monad.Trans import Control.Monad.Writer
main = putStr $ execWriter $ mapM_ (flip execStateT True . fizzbuzz) [1..100]
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"</lang>
Using guards plus where. <lang haskell>fizzBuzz :: (Integral a) => a -> String fizzBuzz i
| fizz && buzz = "FizzBuzz" | fizz = "Fizz" | buzz = "Buzz" | otherwise = show i where fizz = i `mod` 3 == 0 buzz = i `mod` 5 == 0
main = mapM_ (putStrLn . fizzBuzz) [1..100]</lang>
An elegant solution exploiting monoidal and applicative properties of functions: <lang haskell>import Data.Monoid
fizzbuzz = max
<$> show <*> "fizz" `when` divisibleBy 3 <> "buzz" `when` divisibleBy 5 <> "quxx" `when` divisibleBy 7 where when m p x = if p x then m else mempty divisibleBy n x = x `mod` n == 0
main = mapM_ (putStrLn . fizzbuzz) [1..100]</lang>
HicEst
<lang hicest>DO i = 1, 100
IF( MOD(i, 15) == 0 ) THEN WRITE() "FizzBuzz" ELSEIF( MOD(i, 5) == 0 ) THEN WRITE() "Buzz" ELSEIF( MOD(i, 3) == 0 ) THEN WRITE() "Fizz" ELSE WRITE() i ENDIF
ENDDO</lang> Alternatively: <lang hicest>CHARACTER string*8
DO i = 1, 100
string = " " IF( MOD(i, 3) == 0 ) string = "Fizz" IF( MOD(i, 5) == 0 ) string = TRIM(string) // "Buzz" IF( string == " ") WRITE(Text=string) i WRITE() string
ENDDO</lang>
Hoon
<lang Hoon>:- %say |= [^ ~ ~]
:- %noun %+ turn (gulf [1 101]) |= a=@ =+ q=[=(0 (mod a 3)) =(0 (mod a 5))] ?+ q <a> [& &] "FizzBuzz" [& |] "Fizz" [| &] "Buzz" ==</lang>
Hy
<lang lisp>(for [i (range 1 101)] (print (cond
[(not (% i 15)) "FizzBuzz"] [(not (% i 5)) "Buzz"] [(not (% i 3)) "Fizz"] [True i])))</lang>
Icon and Unicon
<lang icon># straight-forward modulo tester procedure main()
every i := 1 to 100 do if i % 15 = 0 then write("FizzBuzz") else if i % 5 = 0 then write("Buzz") else if i % 3 = 0 then write("Fizz") else write(i)
end</lang> <lang icon># idiomatic modulo tester, 1st alternative procedure main()
every i := 1 to 100 do write((i % 15 = 0 & "FizzBuzz") | (i % 5 = 0 & "Buzz") | (i % 3 = 0 & "Fizz") | i)
end</lang> <lang icon># idiomatic modulo tester, 2nd alternative procedure main()
every i := 1 to 100 do write(case 0 of { i % 15 : "FizzBuzz" i % 5 : "Buzz" i % 3 : "Fizz" default: i })
end</lang> <lang icon># straight-forward buffer builder procedure main()
every i := 1 to 100 do { s := "" if i % 3 = 0 then s ||:= "Fizz" if i % 5 = 0 then s ||:= "Buzz" if s == "" then s := i write(s) }
end</lang> <lang icon># idiomatic buffer builder, 1st alternative procedure main()
every i := 1 to 100 do write("" ~== (if i % 3 = 0 then "Fizz" else "") || (if i % 5 == 0 then "Buzz" else "") | i)
end</lang> <lang icon># idiomatic buffer builder, 2nd alternative procedure main()
every i := 1 to 100 do { s := if i%3 = 0 then "Fizz" else "" s ||:= if i%5 = 0 then "Buzz" write(("" ~= s) | i) }
end</lang>
Idris
<lang idris>fizzBuzz : Nat -> String fizzBuzz n = if (n `mod` 15) == 0 then "FizzBuzz"
else if (n `mod` 3) == 0 then "Fizz" else if (n `mod` 5) == 0 then "Buzz" else show n
main : IO () main = sequence_ $ map (putStrLn . fizzBuzz) [1..100]</lang>
Inform 6
<lang inform6>[ Main i;
for(i = 1: i <= 100: i++) { if(i % 3 == 0) print "Fizz"; if(i % 5 == 0) print "Buzz"; if(i % 3 ~= 0 && i % 5 ~= 0) print i;
print "^"; }
];</lang>
Inform 7
(Does not work in the current version of Inform 7)
<lang inform7>Home is a room.
When play begins: repeat with N running from 1 to 100: let printed be false; if the remainder after dividing N by 3 is 0: say "Fizz"; now printed is true; if the remainder after dividing N by 5 is 0: say "Buzz"; now printed is true; if printed is false, say N; say "."; end the story.</lang>
(Version which is less "programmy", and more in the natural English style of interactive fiction.)
<lang inform7>The space is a room. An item is a kind of thing. In the space are 100 items.
To say the name: let the count be the number of items carried by the player; say "[if the count is the count to the nearest 15]fizzbuzz.[otherwise if the count is the count to the nearest 3]fizz.[otherwise if the count is the count to the nearest 5]buzz.[otherwise][the count in words].".
To count: if an item is in the space begin; let the next one be a random item in the space; silently try taking the next one; say "[the name]" in sentence case; count; end the story; end if.
When play begins: count. Use no scoring.</lang>
Io
Here's one way to do it: <lang io>for(a,1,100,
if(a % 15 == 0) then( "FizzBuzz" println ) elseif(a % 3 == 0) then( "Fizz" println ) elseif(a % 5 == 0) then( "Buzz" println ) else ( a println )
)</lang> And here's a port of the Ruby version, which I personally prefer: <lang io>a := 0; b := 0 for(n, 1, 100,
if(a = (n % 3) == 0, "Fizz" print); if(b = (n % 5) == 0, "Buzz" print); if(a not and b not, n print); "\n" print
)</lang> And here is another more idiomatic version: <lang Io>for (n, 1, 100,
fb := list ( if (n % 3 == 0, "Fizz"), if (n % 5 == 0, "Buzz")) select (isTrue) if (fb isEmpty, n, fb join) println
)</lang>
Ioke
<lang ioke>(1..100) each(x,
cond( (x % 15) zero?, "FizzBuzz" println, (x % 3) zero?, "Fizz" println, (x % 5) zero?, "Buzz" println )
)</lang>
Iptscrae
<lang iptscrae>; FizzBuzz in Iptscrae 1 a = {
"" b = { "fizz" b &= } a 3 % 0 == IF { "buzz" b &= } a 5 % 0 == IF { a ITOA LOGMSG } { b LOGMSG } b STRLEN 0 == IFELSE a ++
} { a 100 <= } WHILE</lang>
J
Solution _1: Using agenda (@.) as a switch: <lang j>
classify =: +/@(1 2 * 0 = 3 5&|~) (":@]`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_) @. classify "0) >:i.100
</lang> Solution 0 <lang j>> }. (<'FizzBuzz') (I.0=15|n)} (<'Buzz') (I.0=5|n)} (<'Fizz') (I.0=3|n)} ":&.> n=: i.101</lang> Solution 1 <lang j>Fizz=: 'Fizz' #~ 0 = 3&| Buzz=: 'Buzz' #~ 0 = 5&| FizzBuzz=: ": [^:( -: ]) Fizz,Buzz
FizzBuzz"0 >: i.100</lang> Solution 2 (has taste of table-driven template programming) <lang j>CRT0=: 2 : ' (, 0 = +./)@(0 = m | ]) ;@# n , <@": ' NB. Rather (, 0 = +./) than (, +:/) because designed for NB. 3 5 7 CRT0 (;:'Chinese Remainder Period') "0 >: i. */3 5 7 FizzBuzz=: 3 5 CRT0 (;:'Fizz Buzz')
FizzBuzz"0 >: i.100</lang> Solution 3 (depends on an obsolete feature of @ in f`g`h@p) <lang j>'`f b fb' =: ('Fizz'"_) ` ('Buzz'"_) ` (f , b) '`cm3 cm5 cm15'=: (3&|) ` (5&|) ` (15&|) (0&=@) FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` fb @. cm15 NB. also: FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` (f,b) @. (cm3 *. cm5)
FizzBuzz"0 >: i.100</lang>
Solution 4 (relatively concise):
<lang J> ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~ 0 = 3 5 |/ ])i.101 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 Fiz...</lang>
Here's some intermediate results for subexpressions of this last version (but with a shorter list of numbers):
<lang J> i.10 0 1 2 3 4 5 6 7 8 9
(3 5 |/ ])i.10
0 1 2 0 1 2 0 1 2 0 0 1 2 3 4 0 1 2 3 4
(0=3 5 |/ ])i.10
1 0 0 1 0 0 1 0 0 1 1 0 0 0 0 1 0 0 0 0
(;:'Fizz Buzz')
┌────┬────┐ │Fizz│Buzz│ └────┴────┘
((;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
┌────┬┬┬────┬┬────┬────┬┬┬────┐ │Fizz│││Fizz││ │Fizz│││Fizz│ ├────┼┼┼────┼┼────┼────┼┼┼────┤ │Buzz│││ ││Buzz│ │││ │ └────┴┴┴────┴┴────┴────┴┴┴────┘
([: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
┌────────┬┬┬────┬┬────┬────┬┬┬────┐ │FizzBuzz│││Fizz││Buzz│Fizz│││Fizz│ └────────┴┴┴────┴┴────┴────┴┴┴────┘
(":&.>)i.10
┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ │0│1│2│3│4│5│6│7│8│9│ └─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘
(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
┌────────┬─┬─┬────┬─┬────┬────┬─┬─┬────┐ │FizzBuzz│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│ └────────┴─┴─┴────┴─┴────┴────┴─┴─┴────┘
}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
┌─┬─┬────┬─┬────┬────┬─┬─┬────┐ │1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│ └─┴─┴────┴─┴────┴────┴─┴─┴────┘
;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
1 2 Fizz 4 Buzz Fizz 7 8 Fizz</lang>
Java
See FizzBuzz/Java
JavaScript
<lang javascript>var fizzBuzz = function () {
var i, output; for (i = 1; i < 101; i += 1) { output = ; if (!(i % 3)) { output += 'Fizz'; } if (!(i % 5)) { output += 'Buzz'; } console.log(output || i);//empty string is false, so we short-circuit }
};</lang>
Alternate version with ghetto pattern matching <lang javascript>for (var i = 1; i <= 100; i++) {
console.log({ truefalse: 'Fizz', falsetrue: 'Buzz', truetrue: 'FizzBuzz' }[(i%3==0) + + (i%5==0)] || i)
}</lang>
Or very tersely: <lang javascript> for(i=1;i<101;i++)console.log((x=(i%3?:'Fizz')+(i%5?:'Buzz'))?x:i); </lang>
or, in a more functional style, without mutations <lang javascript>(function rng(i) {
return i ? rng(i - 1).concat(i) : []
})(100).map(
function (n) { return n % 3 ? ( n % 5 ? n : "Buzz" ) : ( n % 5 ? "Fizz" : "FizzBuzz" ) }
).join(' ')</lang>
Joy
The following program first defines a function "one", which handles the Fizz / Buzz logic, and then loops from 1 to 100 mapping the function onto each number, and printing ("put") the output. <lang Joy>DEFINE one == [[[dup 15 rem 0 =] "FizzBuzz"] [[dup 3 rem 0 =] "Fizz"] [[dup 5 rem 0 =] "Buzz"] [dup]] cond. 1 [100 <=] [dup one put succ] while.</lang>
jq
<lang jq>range(1;101)
| if . % 15 == 0 then "FizzBuzz" elif . % 5 == 0 then "Buzz" elif . % 3 == 0 then "Fizz" else . end</lang>
Another solution:
<lang jq>range(100) + 1 | [( (select(. % 3 == 0) | "Fizz"), (select(. % 5 == 0) | "Buzz") ) // tostring] | join("") </lang>
Julia
<lang Julia>for i = 1:100
if i % 15 == 0 println("FizzBuzz") elseif i % 3 == 0 println("Fizz") elseif i % 5 == 0 println("Buzz") else println(i) end
end</lang> Another solution <lang Julia>println( [ i%15 == 0? "FizzBuzz" :
i%5 == 0? "Buzz" : i%3 == 0? "Fizz" : i for i = 1:100 ] )</lang>
Yet another solution <lang Julia>fb(i::Int) = "Fizz" ^ (i%3==0) *
"Buzz" ^ (i%5==0) * string(i) ^ (i%3!=0 && i%5!=0)
for i=1:100 println(fb(i)) end</lang> Another one <lang Julia>map((x) -> x % 15 == 0 ? "FizzBuzz" : (x % 5 == 0 ? "Buzz" : (x % 3 == 0 ? "Fizz" : x)), 1:100)</lang> The next solution is a bit more flexible. There is no need to test divisibility by 15 and we can easily extend the code to handle, say, divisibility by 7.
<lang Julia>fib(i) = let result = ""
(i%3 == 0 && (result *="Fizz" ; true)) | (i%5 == 0 && (result *="Buzz" ; true)) || (result = string(i)) result end
println([fib(i) for i = 1:100])</lang> Another DRY* solution that can easily accommodate further divisibility tests. *DRY = Don't Repeat Yourself. <lang Julia>for i = 1:100
msg = "Fizz" ^ (i%3==0) * "Buzz" ^ (i%5==0) println(msg=="" ? i : msg)
end</lang>
K
Solution 0
<lang k>`0:\:{:[0=#a:{,/$(:[0=x!3;"Fizz"];:[0=x!5;"Buzz"])}@x;$x;a]}'1_!101</lang>
Solution 1
<lang k>
fizzbuzz:{:[0=x!15;`0:,"FizzBuzz";0=x!3;`0:,"Fizz";0=x!5;`0:,"Buzz";`0:,$x]} fizzbuzz' 1+!100
</lang>
Solution 2
<lang k>fizzbuzz:{
v:1+!x i:(&0=)'v!/:3 5 15 r:@[v;i 0;{"Fizz"}] r:@[r;i 1;{"Buzz"}] @[r;i 2;{"FizzBuzz"}]}
`0:$fizzbuzz 100</lang>
Kamailio Script
To run it, send a SIP message to the server and FizzBuzz will appear in the logs.
This will only work up to 100 because Kamailio terminates all while loops after 100 iterations. <lang kamailio># FizzBuzz log_stderror=yes loadmodule "pv" loadmodule "xlog"
route {
$var(i) = 1; while ($var(i) <= 1000) { if ($var(i) mod 15 == 0) { xlog("FizzBuzz\n"); } else if ($var(i) mod 5 == 0) { xlog("Buzz\n"); } else if ($var(i) mod 3 == 0) { xlog("Fizz\n"); } else { xlog("$var(i)\n"); } $var(i) = $var(i) + 1; }
}</lang>
Kaya
<lang kaya>// fizzbuzz in Kaya program fizzbuzz;
Void fizzbuzz(Int size) {
for i in [1..size] { if (i % 15 == 0) { putStrLn("FizzBuzz"); } else if (i % 5 == 0) { putStrLn("Buzz"); } else if (i % 3 == 0) { putStrLn("Fizz"); } else { putStrLn( string(i) ); } }
}
Void main() {
fizzbuzz(100);
}</lang>
Klong
<lang k> {[fizzy buzzy fizzybuzzy]; fizzy::x!3; buzzy::x!5; fizzybuzzy::(fizzy+buzzy); :[0=fizzybuzzy;.d("FizzBuzz") :|0=fizzy; .d("Fizz") :|0=buzzy; .d("Buzz"); .d(x)]; .d(" ")}'1+!100</lang>
Kotlin
Imperative solution
<lang kotlin>fun fizzBuzz() {
for (i in 1..100) { when { i % 15 == 0 -> println("FizzBuzz") i % 3 == 0 -> println("Fizz") i % 5 == 0 -> println("Buzz") else -> println(i) } }
}</lang>
Functional solution 1
<lang kotlin>fun fizzBuzz() {
fun fizzbuzz(x: Int) = if(x % 15 == 0) "FizzBuzz" else x fun fizz(x: Any) = if(x is Int && x % 3 == 0) "Buzz" else x fun buzz(x: Any) = if(x is Int && x.toInt() % 5 == 0) "Fizz" else x
(1..100).map { fizzbuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) }
}</lang>
Functional solution 2
<lang kotlin>fun fizzBuzz() {
fun fizz(x: Pair<Int, StringBuilder>) = if(x.first % 3 == 0) x.apply { second.append("Fizz") } else x fun buzz(x: Pair<Int, StringBuilder>) = if(x.first % 5 == 0) x.apply { second.append("Buzz") } else x fun none(x: Pair<Int, StringBuilder>) = if(x.second.isBlank()) x.second.apply { append(x.first) } else x.second
(1..100).map { Pair(it, StringBuilder()) } .map { fizz(it) } .map { buzz(it) } .map { none(it) } .forEach { println(it) }
}</lang>
LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Lasso
<lang lasso>with i in generateSeries(1, 100) select ((#i % 3 == 0 ? 'Fizz' | ) + (#i % 5 == 0 ? 'Buzz' | ) || #i)</lang>
LaTeX
This version uses the ifthen and intcalc packages. There sure are more native solutions including solutions in plain TeX, but for me this is a readable and comprehensible one. <lang LaTeX>\documentclass{minimal} \usepackage{ifthen} \usepackage{intcalc}
\newcounter{mycount} \newboolean{fizzOrBuzz}
\newcommand\fizzBuzz[1]{% \setcounter{mycount}{1}\whiledo{\value{mycount}<#1}
{
\setboolean{fizzOrBuzz}{false} \ifthenelse{\equal{\intcalcMod{\themycount}{3}}{0}}{\setboolean{fizzOrBuzz}{true}Fizz}{} \ifthenelse{\equal{\intcalcMod{\themycount}{5}}{0}}{\setboolean{fizzOrBuzz}{true}Buzz}{} \ifthenelse{\boolean{fizzOrBuzz}}{}{\themycount} \stepcounter{mycount} \\
}
}
\begin{document}
\fizzBuzz{101}
\end{document}</lang>
Liberty BASIC
See FizzBuzz/Basic
LiveCode
<lang LiveCode>repeat with i = 1 to 100
switch case i mod 15 = 0 put "FizzBuzz" & cr after fizzbuzz break case i mod 5 = 0 put "Buzz" & cr after fizzbuzz break case i mod 3 = 0 put "Fizz" & cr after fizzbuzz break default put i & cr after fizzbuzz end switch
end repeat put fizzbuzz</lang>
LiveScript
See: http://livescript.net/blog/fizzbuzzbazz.html <lang LiveScript>[1 to 100] map -> [k + \zz for k, v of {Fi: 3, Bu: 5} | it % v < 1] * || it</lang>
Lobster
<lang Lobster>include "std.lobster"
forbias(100, 1) i:
fb := (i % 3 == 0 and "fizz" or "") + (i % 5 == 0 and "buzz" or "") print fb.length and fb or "" + i</lang>
Logo
<lang logo>to fizzbuzz :n
output cond [ [[equal? 0 modulo :n 15] "FizzBuzz] [[equal? 0 modulo :n 5] "Buzz] [[equal? 0 modulo :n 3] "Fizz] [else :n] ]
end
repeat 100 [print fizzbuzz #]</lang> "cond" was undefined in Joshua Bell's online interpreter. So here is a version that works there. It also works in UCB logo by using # instead of "repcount". This version also factors away modulo 15: <lang logo>to fizzbuzz :n
make "c " if equal? 0 modulo :n 5 [make "c "Buzz] if equal? 0 modulo :n 3 [make "c word "Fizz :c] output ifelse equal? :c " [:n] [:c]
end
repeat 100 [print fizzbuzz repcount]</lang> Lhogho can use the above code, except that 'modulo' must be replaced with 'remainder'.
LOLCODE
See FizzBuzz/EsoLang
LSE
<lang LSE>1* FIZZBUZZ en L.S.E. 10 CHAINE FB 20 FAIRE 45 POUR I_1 JUSQUA 100 30 FB_SI &MOD(I,3)=0 ALORS SI &MOD(I,5)=0 ALORS 'FIZZBUZZ' SINON 'FIZZ' SINON SI &MOD(I,5)=0 ALORS 'BUZZ' SINON 40 AFFICHER[U,/] SI FB= ALORS I SINON FB 45*FIN BOUCLE 50 TERMINER 100 PROCEDURE &MOD(A,B) LOCAL A,B 110 RESULTAT A-B*ENT(A/B)</lang>
Lua
If/else Ladder
<lang Lua>for i = 1, 100 do if i % 15 == 0 then print("FizzBuzz") elseif i % 3 == 0 then print("Fizz") elseif i % 5 == 0 then print("Buzz") else print(i) end end</lang>
Concatenation
<lang Lua>for i = 1, 100 do output = "" if i % 3 == 0 then output = output.."Fizz" end if i % 5 == 0 then output = output.."Buzz" end if(output == "") then output = i end print(output) end</lang>
Quasi bit field
<lang Lua>word = {"Fizz", "Buzz", "FizzBuzz"}
for i = 1, 100 do
print(word[(i % 3 == 0 and 1 or 0) + (i % 5 == 0 and 2 or 0)] or i)
end</lang>
Luck
<lang Luck>for i in range(1,101) do (
if i%15 == 0 then print("FizzBuzz") else if i%3 == 0 then print("Fizz") else if i%5 == 0 then print("Buzz") else print(i)
)</lang>
M4
<lang M4>define(`for',
`ifelse($#,0,``$0, `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')
for(`x',1,100,1,
`ifelse(eval(x%15==0),1,FizzBuzz, `ifelse(eval(x%3==0),1,Fizz, `ifelse(eval(x%5==0),1,Buzz,x)')')
')</lang>
make
<lang make>MOD3 = 0 MOD5 = 0 ALL != jot 100
all: say-100
.for NUMBER in $(ALL)
MOD3 != expr \( $(MOD3) + 1 \) % 3; true MOD5 != expr \( $(MOD5) + 1 \) % 5; true
. if "$(NUMBER)" > 1 PRED != expr $(NUMBER) - 1 say-$(NUMBER): say-$(PRED) . else say-$(NUMBER): . endif . if "$(MOD3)$(MOD5)" == "00" @echo FizzBuzz . elif "$(MOD3)" == "0" @echo Fizz . elif "$(MOD5)" == "0" @echo Buzz . else @echo $(NUMBER) . endif
.endfor</lang>
Maple
One line: <lang Maple>seq(print(`if`(modp(n,3)=0,`if`(modp(n,15)=0,"FizzBuzz","Fizz"),`if`(modp(n,5)=0,"Buzz",n))),n=1..100):</lang> With a fizzbuzz function defined: <lang Maple>fizzbuzz1 := n->`if`(modp(n,3)=0,`if`(modp(n,15)=0,"FizzBuzz","Fizz"),`if`(modp(n,5)=0,"Buzz",n)): for i to 100 do fizzbuzz1(i); od;</lang> Using piecewise: <lang Maple>fizzbuzz2 := n->piecewise(modp(n,15)=0,"FizzBuzz",modp(n,3)=0,"Fizz",modp(n,5)=0,"Buzz",n): for i to 100 do fizzbuzz2(i); od;</lang> Using conventional if/then branches: <lang Maple>fizzbuzz3 := proc(n) local r;
r:=map2(modp,n,[3,5]); if r=[0,0] then "FizzBuzz" elif r[1]=0 then "Fizz" elif r[2]=0 then "Buzz" else n fi;
end proc: for i to 100 do fizzbuzz3(i); od;</lang>
Mathematica / Wolfram Language
<lang Mathematica>Do[Print[Which[Mod[i, 15] == 0, "FizzBuzz", Mod[i, 5] == 0, "Buzz", Mod[i, 3] == 0, "Fizz", True, i]], {i, 100}]</lang> Using rules, <lang Mathematica>fizz[i_] := Mod[i, 3] == 0 buzz[i_] := Mod[i, 5] == 0 Range[100] /. {i_ /; fizz[i]&&buzz[i] :> "FizzBuzz", \
i_?fizz :> "Fizz", i_?buzz :> "Buzz"}</lang>
Using rules, but different approach: <lang Mathematica>SetAttributes[f,Listable] f[n_ /; Mod[n, 15] == 0] := "FizzBuzz"; f[n_ /; Mod[n, 3] == 0] := "Fizz"; f[n_ /; Mod[n, 5] == 0] := "Buzz"; f[n_] := n;
f[Range[100]]</lang> An extendible version using Table <lang Mathematica>Table[If[# === "", i, #]&@StringJoin[
Table[If[Divisible[i, First@nw], Last@nw, ""], {nw, {{3, "Fizz"}, {5, "Buzz"}}}]], {i, 1, 100}]</lang>
Another one-liner using Map (the /@ operator shorthand of it) and a pure function with a very readable Which <lang Mathematica> Which[ Mod[#,15] == 0, "FizzBuzz", Mod[#, 3] == 0, "Fizz", Mod[#,5]==0, "Buzz", True, #]& /@ Range[1,100] </lang>
MATLAB
There are more sophisticated solutions to this task, but in the spirit of "lowest level of comprehension required to illustrate adequacy" this is what one might expect from a novice programmer (with a little variation in how the strings are stored and displayed). <lang MATLAB>function fizzBuzz()
for i = (1:100) if mod(i,15) == 0 fprintf('FizzBuzz ') elseif mod(i,3) == 0 fprintf('Fizz ') elseif mod(i,5) == 0 fprintf('Buzz ') else fprintf('%i ',i)) end end fprintf('\n');
end</lang> Here's a more extendible version that uses disp() to print the output: <lang MATLAB>function out = fizzbuzzS() nums = [3, 5]; words = {'fizz', 'buzz'}; for (n=1:100) tempstr = ; for (i = 1:2) if mod(n,nums(i))==0 tempstr = [tempstr, words{i}]; end end if length(tempstr) == 0 disp(n); else disp(tempstr); end end end</lang>
Maxima
<lang maxima>for n thru 100 do
if mod(n, 15) = 0 then disp("FizzBuzz") elseif mod(n, 3) = 0 then disp("Fizz") elseif mod(n,5) = 0 then disp("Buzz") else disp(n);</lang>
MAXScript
<lang maxscript>for i in 1 to 100 do (
case of ( (mod i 15 == 0): (print "FizzBuzz") (mod i 5 == 0): (print "Buzz") (mod i 3 == 0): (print "Fizz") default: (print i) )
)</lang>
MEL
<lang mel>for($i=1; $i<=100; $i++) {
if($i % 15 == 0) print "FizzBuzz\n"; else if ($i % 3 == 0) print "Fizz\n"; else if ($i % 5 == 0) print "Buzz\n"; else print ($i + "\n");
}</lang>
Mercury
<lang mercury>:- module fizzbuzz.
- - interface.
- - import_module io.
- - pred main(io::di, io::uo) is det.
- - implementation.
- - import_module int, string, bool.
- - func fizz(int) = bool.
fizz(N) = ( if N mod 3 = 0 then yes else no ).
- - func buzz(int) = bool.
buzz(N) = ( if N mod 5 = 0 then yes else no ).
% N 3? 5?
- - func fizzbuzz(int, bool, bool) = string.
fizzbuzz(_, yes, yes) = "FizzBuzz". fizzbuzz(_, yes, no) = "Fizz". fizzbuzz(_, no, yes) = "Buzz". fizzbuzz(N, no, no) = from_int(N).
main(!IO) :- main(1, 100, !IO).
- - pred main(int::in, int::in, io::di, io::uo) is det.
main(N, To, !IO) :-
io.write_string(fizzbuzz(N, fizz(N), buzz(N)), !IO), io.nl(!IO), ( N < To -> main(N + 1, To, !IO) ; !:IO = !.IO ).</lang>
Metafont
<lang metafont>for i := 1 upto 100: message if i mod 15 = 0: "FizzBuzz" & elseif i mod 3 = 0: "Fizz" & elseif i mod 5 = 0: "Buzz" & else: decimal i & fi ""; endfor end</lang>
Mirah
<lang mirah>1.upto(100) do |n|
print "Fizz" if a = ((n % 3) == 0) print "Buzz" if b = ((n % 5) == 0) print n unless (a || b) print "\n"
end</lang>
A little more straight forward: <lang mirah>1.upto(100) do |n|
if (n % 15) == 0 puts "FizzBuzz" elsif (n % 5) == 0 puts "Buzz" elsif (n % 3) == 0 puts "Fizz" else puts n end
end</lang>
ML
Standard ML
First using two helper functions, one for deciding what to output and another for performing recursion with an auxiliary argument j. <lang sml>local
fun fbstr i = case (i mod 3 = 0, i mod 5 = 0) of (true , true ) => "FizzBuzz" | (true , false) => "Fizz" | (false, true ) => "Buzz" | (false, false) => Int.toString i
fun fizzbuzz' (n, j) = if n = j then () else (print (fbstr j ^ "\n"); fizzbuzz' (n, j+1))
in
fun fizzbuzz n = fizzbuzz' (n, 1) val _ = fizzbuzz 100
end</lang>
Second using the standard-library combinator List.tabulate and a helper function, fb, that calculates and prints the output. <lang sml>local
fun fb i = let val fizz = i mod 3 = 0 andalso (print "Fizz"; true) val buzz = i mod 5 = 0 andalso (print "Buzz"; true) in fizz orelse buzz orelse (print (Int.toString i); true) end
in
fun fizzbuzz n = (List.tabulate (n, fn i => (fb (i+1); print "\n")); ()) val _ = fizzbuzz 100
end</lang>
mLite
<lang ocaml>local fun fizzbuzz' (x mod 15 = 0) = "FizzBuzz" | (x mod 5 = 0) = "Buzz" | (x mod 3 = 0) = "Fizz" | x = ntos x in fun fizzbuzz ([], s) = rev s | (x :: xs, s) = fizzbuzz (xs, fizzbuzz' x :: s) | (x :: xs) = fizzbuzz (x :: xs, []) end
println ` fizzbuzz ` iota 100; </lang>
MMIX
<lang mmix>t IS $255 Ja IS $127
LOC Data_Segment
data GREG @
fizz IS @-Data_Segment
BYTE "Fizz",0,0,0,0
buzz IS @-Data_Segment
BYTE "Buzz",0,0,0,0
nl IS @-Data_Segment
BYTE #a,0,0,0,0,0,0,0
buffer IS @-Data_Segment
LOC #1000 GREG @
% "usual" print integer subroutine printnum LOC @
OR $1,$0,0 SETL $2,buffer+64 ADDU $2,$2,data XOR $3,$3,$3 STBU $3,$2,1
loop DIV $1,$1,10
GET $3,rR ADDU $3,$3,'0' STBU $3,$2,0 SUBU $2,$2,1 PBNZ $1,loop ADDU t,$2,1 TRAP 0,Fputs,StdOut GO Ja,Ja,0
Main SETL $0,1 % i = 1 1H SETL $2,0 % fizz not taken
CMP $1,$0,100 % i <= 100 BP $1,4F % if no, go to end DIV $1,$0,3 GET $1,rR % $1 = mod(i,3) CSZ $2,$1,1 % $2 = Fizz taken? BNZ $1,2F % $1 != 0? yes, then skip ADDU t,data,fizz TRAP 0,Fputs,StdOut % print "Fizz"
2H DIV $1,$0,5
GET $1,rR % $1 = mod(i,5) BNZ $1,3F % $1 != 0? yes, then skip ADDU t,data,buzz TRAP 0,Fputs,StdOut % print "Buzz" JMP 5F % skip print i
3H BP $2,5F % skip if Fizz was taken
GO Ja,printnum % print i
5H ADDU t,data,nl
TRAP 0,Fputs,StdOut % print newline ADDU $0,$0,1 JMP 1B % repeat for next i
4H XOR t,t,t
TRAP 0,Halt,0 % exit(0)</lang>
Modula-3
<lang modula3>MODULE Fizzbuzz EXPORTS Main;
IMPORT IO;
BEGIN
FOR i := 1 TO 100 DO IF i MOD 15 = 0 THEN IO.Put("FizzBuzz\n"); ELSIF i MOD 5 = 0 THEN IO.Put("Buzz\n"); ELSIF i MOD 3 = 0 THEN IO.Put("Fizz\n"); ELSE IO.PutInt(i); IO.Put("\n"); END; END;
END Fizzbuzz.</lang>
Monte
<lang Monte>def fizzBuzz(top):
var t := 1 while (t < top): if ((t % 3 == 0) || (t % 5 == 0)): if (t % 15 == 0): traceln(`$t FizzBuzz`) else if (t % 3 == 0): traceln(`$t Fizz`) else: traceln(`$t Buzz`) t += 1
fizzBuzz(100) </lang>
MoonScript
<lang moonscript>for i = 1,100
print ((a) -> a == "" and i or a) table.concat { i % 3 == 0 and "Fizz" or "" i % 5 == 0 and "Buzz" or ""}</lang>
MUMPS
<lang MUMPS>FIZZBUZZ
NEW I FOR I=1:1:100 WRITE !,$SELECT(('(I#3)&'(I#5)):"FizzBuzz",'(I#5):"Buzz",'(I#3):"Fizz",1:I) KILL I QUIT</lang>
<lang MUMPS>fizzbuzz
for i=1:1:100 do write ! . write:(i#3)&(i#5) i write:'(i#3) "Fizz" write:'(i#5) "Buzz"</lang>
Neko
<lang Neko>var i = 1
while(i < 100) { if(i % 15 == 0) { $print("FizzBuzz\n"); } else if(i % 3 == 0) { $print("Fizz\n"); } else if(i % 5 == 0) { $print("Buzz\n"); } else { $print(i + "\n"); }
i ++= 1 }</lang>
Nemerle
The naive approach: <lang Nemerle>using System; using System.Console;
module FizzBuzz {
FizzBuzz(x : int) : string { |x when x % 15 == 0 => "FizzBuzz" |x when x % 5 == 0 => "Buzz" |x when x % 3 == 0 => "Fizz" |_ => $"$x" } Main() : void { foreach (i in [1 .. 100]) WriteLine($"$(FizzBuzz(i))") }
}</lang> A much slicker approach is posted here
NetRexx
<lang netrexx>loop j=1 for 100
select when j//15==0 then say 'FizzBuzz' when j//5==0 then say 'Buzz' when j//3==0 then say 'Fizz' otherwise say j.right(4) end
end</lang>
NewtonScript
<lang newton>for i := 1 to 100 do begin if i mod 15 = 0 then print("FizzBuzz") else if i mod 3 = 0 then print("Fizz") else if i mod 5 = 0 then print("Buzz") else print(i); print("\n") end</lang>
Nickle
<lang nickle>/* Fizzbuzz in nickle */
void function fizzbuzz(size) {
for (int i = 1; i < size; i++) { if (i % 15 == 0) { printf("Fizzbuzz\n"); } else if (i % 5 == 0) { printf("Buzz\n"); } else if (i % 3 == 0) { printf("Fizz\n"); } else { printf("%i\n", i); } }
}
fizzbuzz(1000);</lang>
NewLISP
<lang NewLISP>(dotimes (i 100)
(println (cond ((= 0 (% i 15)) "FizzBuzz") ((= 0 (% i 3)) "Fizz") ((= 0 (% i 5)) "Buzz") ('t i))))</lang>
Nim
<lang nim>for i in 1..100:
if i mod 15 == 0: echo("FizzBuzz") elif i mod 3 == 0: echo("Fizz") elif i mod 5 == 0: echo("Buzz") else: echo(i)</lang>
Without Modulus
<lang nim>var messages = @["", "Fizz", "Buzz", "FizzBuzz"] var acc = 810092048 for i in 1..100:
var c = acc and 3 echo(if c == 0: $i else: messages[c]) acc = acc shr 2 or c shl 28</lang>
Using macro
Computes everything at compile time. <lang nim>import macros macro FizzBuzz(N): stmt =
var source = "" for i in 1..N.intVal: source &= "echo \"" if i mod 15 == 0: source &= "FizzBuzz" elif i mod 3 == 0: source &= "Fizz" elif i mod 5 == 0: source &= "Buzz" else: source &= $i source &= "\"\n" result = parseStmt(source)
FizzBuzz(100)</lang>
Oberon-2
<lang oberon2>MODULE FizzBuzz;
IMPORT Out;
VAR i: INTEGER;
BEGIN
FOR i := 1 TO 100 DO IF i MOD 15 = 0 THEN Out.String("FizzBuzz"); Out.Ln; ELSIF i MOD 5 = 0 THEN Out.String("Buzz"); Out.Ln; ELSIF i MOD 3 = 0 THEN Out.String("Fizz"); Out.Ln; ELSE Out.Int(i,0); Out.Ln; END; END;
END FizzBuzz.</lang>
Objeck
<lang objeck>bundle Default {
class Fizz { function : Main(args : String[]) ~ Nil { for(i := 0; i <= 100; i += 1;) { if(i % 15 = 0) { "FizzBuzz"->PrintLine(); } else if(i % 3 = 0) { "Fizz"->PrintLine(); } else if(i % 5 = 0) { "Buzz"->PrintLine(); } else { i->PrintLine(); }; }; } }
}</lang>
Objective-C
<lang c>// FizzBuzz in Objective-C
- import <stdio.h>
main() { for (int i=1; i<=100; i++) { if (i % 15 == 0) { printf("FizzBuzz\n"); } else if (i % 3 == 0) { printf("Fizz\n"); } else if (i % 5 == 0) { printf("Buzz\n"); } else { printf("%i\n", i); } } }</lang>
OCaml
Idiomatic OCaml to solve the stated problem:
<lang ocaml>let fizzbuzz i =
match i mod 3, i mod 5 with 0, 0 -> "FizzBuzz" | 0, _ -> "Fizz" | _, 0 -> "Buzz" | _ -> string_of_int i
let _ =
for i = 1 to 100 do print_endline (fizzbuzz i) done</lang>
With a view toward extensibility, there are many approaches: monadic, list of rules, ... here we'll use a piped sequence of rules to define a new "fizzbuzz" function:
<lang ocaml>(* Useful rule declaration: "cond => f", 'cond'itionally applies 'f' to 'a'ccumulated value *) let (=>) cond f a = if cond then f a else a let append s a = a^s
let fizzbuzz i =
"" |> (i mod 3 = 0 => append "Fizz") |> (i mod 5 = 0 => append "Buzz") |> (function "" -> string_of_int i | s -> s)</lang>
Octave
<lang octave>for i = 1:100
if ( mod(i,15) == 0 ) disp("FizzBuzz"); elseif ( mod(i, 3) == 0 ) disp("Fizz") elseif ( mod(i, 5) == 0 ) disp("Buzz") else disp(i) endif
endfor</lang>
Oforth
<lang Oforth>: fizzbuzz | i |
100 loop: i [ null i 3 mod ifZero: [ "Fizz" + ] i 5 mod ifZero: [ "Buzz" + ] dup ifNull: [ drop i ] . ] ; </lang>
OOC
<lang ooc>fizz: func (n: Int) -> Bool {
if(n % 3 == 0) { printf("Fizz") return true } return false
}
buzz: func (n: Int) -> Bool {
if(n % 5 == 0) { printf("Buzz") return true } return false
}
main: func {
for(n in 1..100) { fizz:= fizz(n) buzz:= buzz(n) fizz || buzz || printf("%d", n) println() }
}</lang>
Order
<lang c>#include <order/interpreter.h>
// Get FB for one number
- define ORDER_PP_DEF_8fizzbuzz ORDER_PP_FN( \
8fn(8N, \
8let((8F, 8fn(8N, 8G, \ 8is_0(8remainder(8N, 8G)))), \ 8cond((8ap(8F, 8N, 15), 8quote(fizzbuzz)) \ (8ap(8F, 8N, 3), 8quote(fizz)) \ (8ap(8F, 8N, 5), 8quote(buzz)) \ (8else, 8N)))) )
// Print E followed by a comma (composable, 8print is not a function)
- define ORDER_PP_DEF_8print_el ORDER_PP_FN( \
8fn(8E, 8print(8E 8comma)) )
ORDER_PP( // foreach instead of map, to print but return nothing
8seq_for_each(8compose(8print_el, 8fizzbuzz), 8seq_iota(1, 100))
)</lang>
Oz
<lang oz>declare
fun {FizzBuzz X} if X mod 15 == 0 then 'FizzBuzz' elseif X mod 3 == 0 then 'Fizz' elseif X mod 5 == 0 then 'Buzz' else X end end
in
for I in 1..100 do {Show {FizzBuzz I}} end</lang>
PARI/GP
<lang parigp>{for(n=1,100,
print(if(n%3, if(n%5, n , "Buzz" ) , if(n%5, "Fizz" , "FizzBuzz" ) ))
)}</lang>
Pascal
<lang pascal>program fizzbuzz(output); var
i: integer;
begin
for i := 1 to 100 do if i mod 15 = 0 then writeln('FizzBuzz') else if i mod 3 = 0 then writeln('Fizz') else if i mod 5 = 0 then writeln('Buzz') else writeln(i)
end.</lang>
Peloton
Variable-length padded English dialect <lang sgml><# DEFINE USERDEFINEDROUTINE LITERAL>__FizzBuzz|<# SUPPRESSAUTOMATICWHITESPACE> <# TEST ISITMODULUSZERO PARAMETER LITERAL>1|3</#> <# TEST ISITMODULUSZERO PARAMETER LITERAL>1|5</#> <# ONLYFIRSTOFLASTTWO><# SAY LITERAL>Fizz</#></#> <# ONLYSECONDOFLASTTWO><# SAY LITERAL>Buzz</#></#> <# BOTH><# SAY LITERAL>FizzBuzz</#></#> <# NEITHER><# SAY PARAMETER>1</#></#> </#></#> <# ITERATE FORITERATION LITERAL LITERAL>100|<# ACT USERDEFINEDROUTINE POSITION FORITERATION>__FizzBuzz|...</#> </#></lang> Fixed-length English dialect <lang sgml><@ DEFUDRLIT>__FizzBuzz|<@ SAW> <@ TSTMD0PARLIT>1|3</@> <@ TSTMD0PARLIT>1|5</@> <@ O12><@ SAYLIT>Fizz</@></@> <@ O22><@ SAYLIT>Buzz</@></@> <@ BTH><@ SAYLIT>FizzBuzz</@></@> <@ NTH><@ SAYPAR>1</@></@> </@></@> <@ ITEFORLITLIT>100|<@ ACTUDRPOSFOR>__FizzBuzz|...</@> </@></lang>
Perl
<lang perl> use strict; use warnings; use feature qw(say);
for my $i (1..100) {
say $i % 15 == 0 ? "FizzBuzz" : $i % 3 == 0 ? "Fizz" : $i % 5 == 0 ? "Buzz" : $i;
}</lang>
More concisely:
<lang perl>print 'Fizz'x!($_ % 3) . 'Buzz'x!($_ % 5) || $_, "\n" for 1 .. 100;</lang>
For code-golfing:
<lang perl>print+(Fizz)[$_%3].(Buzz)[$_%5]||$_,$/for 1..1e2</lang>
For array of values:
<lang perl>map((Fizz)[$_%3].(Buzz)[$_%5]||$_,1..100);</lang>
Cheating:
<lang perl> use feature "say";
@a = ("FizzBuzz", 0, 0, "Fizz", 0, "Buzz", "Fizz", 0, 0, "Fizz", "Buzz", 0, "Fizz");
say $a[$_ % 15] || $_ for 1..100;</lang>
Perl 6
Most straightforwardly: <lang perl6>for 1 .. 100 {
when $_ %% (3 & 5) { say 'FizzBuzz'; } when $_ %% 3 { say 'Fizz'; } when $_ %% 5 { say 'Buzz'; } default { .say; }
}</lang> Or abusing multi subs: <lang perl6>multi sub fizzbuzz(Int $ where * %% 15) { 'FizzBuzz' } multi sub fizzbuzz(Int $ where * %% 5) { 'Buzz' } multi sub fizzbuzz(Int $ where * %% 3) { 'Fizz' } multi sub fizzbuzz(Int $number ) { $number } (1 .. 100)».&fizzbuzz.join("\n").say;</lang> Concisely (readable): <lang perl6>say 'Fizz' x $_ %% 3 ~ 'Buzz' x $_ %% 5 || $_ for 1 .. 100;</lang> Shortest FizzBuzz to date: <lang perl6>say "Fizz"x$_%%3~"Buzz"x$_%%5||$_ for 1..100</lang> And here's an implementation that never checks for divisibility: <lang perl6>.say for
( (flat ( xx 2, 'Fizz') xx *) Z~ (flat ( xx 4, 'Buzz') xx *) ) Z|| 1 .. 100;</lang>
Phix
<lang Phix>constant x = {"%d\n","Fizz\n","Buzz\n","FizzBuzz\n"} for i=1 to 100 do
printf(1,x[1+(remainder(i,3)=0)+2*(remainder(i,5)=0)],i)
end for </lang>
PHL
<lang phl>module fizzbuzz;
extern printf;
@Integer main [ var i = 1; while (i <= 100) { if (i % 15 == 0) printf("FizzBuzz"); else if (i % 3 == 0) printf("Fizz"); else if (i % 5 == 0) printf("Buzz"); else printf("%d", i);
printf("\n"); i = i::inc; }
return 0; ]</lang>
PHP
if/else ladder approach
<lang php><?php for ($i = 1; $i <= 100; $i++) {
if (!($i % 15)) echo "FizzBuzz\n"; else if (!($i % 3)) echo "Fizz\n"; else if (!($i % 5)) echo "Buzz\n"; else echo "$i\n";
} ?></lang>
concatenation approach
Uses PHP's concatenation operator (.=) to build the output string. The concatenation operator allows us to add data to the end of a string without overwriting the whole string. Since Buzz will always appear if our number is divisible by five, and Buzz is the second part of "FizzBuzz", we can simply append "Buzz" to our string.
In contrast to the if-else ladder, this method lets us skip the check to see if $i is divisible by both 3 and 5 (i.e. 15). However, we get the added complexity of needing to reset $str to an empty string (not necessary in some other languages), and we also need a separate if statement to check to see if our string is empty, so we know if $i was not divisible by 3 or 5. <lang php><?php for ( $i = 1; $i <= 100; ++$i ) {
$str = "";
if (!($i % 3 ) ) $str .= "Fizz";
if (!($i % 5 ) ) $str .= "Buzz";
if ( empty( $str ) ) $str = $i;
echo $str . "\n";
} ?></lang>
One Liner Approach
<lang php><?php for($i = 1; $i <= 100 and print(($i % 15 ? $i % 5 ? $i % 3 ? $i : 'Fizz' : 'Buzz' : 'FizzBuzz') . "\n"); ++$i); ?></lang>
PicoLisp
We could simply use 'at' here: <lang PicoLisp>(for N 100
(prinl (or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) )</lang>
Or do it the standard way: <lang PicoLisp>(for N 100
(prinl (cond ((=0 (% N 15)) "FizzBuzz") ((=0 (% N 3)) "Fizz") ((=0 (% N 5)) "Buzz") (T N) ) ) )</lang>
Pike
<lang pike>int main(){
for(int i = 1; i <= 100; i++) { if(i % 15 == 0) { write("FizzBuzz\n"); } else if(i % 3 == 0) { write("Fizz\n"); } else if(i % 5 == 0) { write("Buzz\n"); } else { write(i + "\n"); } }
}</lang>
PIR
<lang pir>.sub main :main
.local int f .local int mf .local int skipnum f = 1
LOOP:
if f > 100 goto DONE skipnum = 0 mf = f % 3 if mf == 0 goto FIZZ
FIZZRET:
mf = f % 5 if mf == 0 goto BUZZ
BUZZRET:
if skipnum > 0 goto SKIPNUM print f
SKIPNUM:
print "\n" inc f goto LOOP end
FIZZ:
print "Fizz" inc skipnum goto FIZZRET end
BUZZ:
print "Buzz" inc skipnum goto BUZZRET end
DONE:
end
.end</lang>
PL/I
<lang PL/I>do i = 1 to 100;
select; when (mod(i,15) = 0) put skip list ('FizzBuzz'); when (mod(i,3) = 0) put skip list ('Fizz'); when (mod(i,5) = 0) put skip list ('Buzz'); otherwise put skip list (i); end;
end;</lang>
Pony
<lang pony>use "collections"
actor Main
new create(env: Env) => for i in Range[I32](1, 100) do env.out.print(fizzbuzz(i)) end fun fizzbuzz(n: I32): String => if (n % 15) == 0 then "FizzBuzz" elseif (n % 5) == 0 then "Buzz" elseif (n % 3) == 0 then "Fizz" else n.string() end</lang>
Pop11
<lang pop11>lvars str; for i from 1 to 100 do
if i rem 15 = 0 then 'FizzBuzz' -> str; elseif i rem 3 = 0 then 'Fizz' -> str; elseif i rem 5 = 0 then 'Buzz' -> str; else >< i -> str; endif; printf(str, '%s\n');
endfor;</lang>
PL/SQL
<lang plsql>begin
for i in 1 .. 100 loop case when mod(i, 15) = 0 then dbms_output.put_line('FizzBuzz'); when mod(i, 5) = 0 then dbms_output.put_line('Buzz'); when mod(i, 3) = 0 then dbms_output.put_line('Fizz'); else dbms_output.put_line(i); end case; end loop;
end;</lang>
PostScript
<lang postscript>1 1 100 { /c false def dup 3 mod 0 eq { (Fizz) print /c true def } if dup 5 mod 0 eq { (Buzz) print /c true def } if
c {pop}{( ) cvs print} ifelse (\n) print
} for</lang> or... <lang postscript>/fizzdict 100 dict def fizzdict begin /notmod{ ( ) cvs } def /mod15 { dup 15 mod 0 eq { (FizzBuzz)def }{pop}ifelse} def /mod3 { dup 3 mod 0 eq {(Fizz)def}{pop}ifelse} def /mod5 { dup 5 mod 0 eq {(Buzz)def}{pop}ifelse} def 1 1 100 { mod3 } for 1 1 100 { mod5 } for 1 1 100 { mod15} for 1 1 100 { dup currentdict exch known { currentdict exch get}{notmod} ifelse print (\n) print} for end</lang>
Potion
<lang lua> 1 to 100 (a):
if (a % 15 == 0): 'FizzBuzz'. elsif (a % 3 == 0): 'Fizz'. elsif (a % 5 == 0): 'Buzz'. else: a. string print "\n" print.</lang>
PowerShell
Straightforward, looping
<lang powershell>for ($i = 1; $i -le 100; $i++) {
if ($i % 15 -eq 0) { "FizzBuzz" } elseif ($i % 5 -eq 0) { "Buzz" } elseif ($i % 3 -eq 0) { "Fizz" } else { $i }
}</lang>
Pipeline, Switch
<lang powershell>$txt=$null 1..100 | ForEach-Object {
switch ($_) { { $_ % 3 -eq 0 } { $txt+="Fizz" } { $_ % 5 -eq 0 } { $txt+="Buzz" } $_ { if($txt) { $txt } else { $_ }; $txt=$null } }
}</lang>
Concatenation
<lang powershell>1..100 | ForEach-Object {
$s = if ($_ % 3 -eq 0) { $s += "Fizz" } if ($_ % 5 -eq 0) { $s += "Buzz" } if (-not $s) { $s = $_ } $s
}</lang>
Filter, Piping, Regex Matching, Array Auto-Selection
<lang powershell> filter fizz-buzz{
@( $_, "Fizz", "Buzz", "FizzBuzz" )[ 2 * ($_ -match '[05]$') + ($_ -match '(^([369][0369]?|[258][147]|[147][258]))$') ]
}
1..100 | fizz-buzz </lang>
Processing
Visualization & Console, Straightforward
Reserved variable "width" in Processing is 100 pixels by default, suitable for this FizzBuzz exercise. Accordingly, range is pixel index from 0 to 99. <lang Processing>for (int i = 0; i < width; i++) {
if (i % 3 == 0 && i % 5 == 0) { stroke(255, 255, 0); println("FizzBuzz!"); } else if (i % 5 == 0) { stroke(0, 255, 0); println("Buzz"); } else if (i % 3 == 0) { stroke(255, 0, 0); println("Fizz"); } else { stroke(0, 0, 255); println(i); } line(i, 0, i, height);
}</lang>
Visualization & Console, Ternary
<lang Processing>for (int i = 0; i < width; i++) {
stroke((i % 5 == 0 && i % 3 == 0) ? #FFFF00 : (i % 5 == 0) ? #00FF00 : (i % 3 == 0) ? #FF0000 : #0000FF); line(i, 0, i, height); println((i % 5 == 0 && i % 3 == 0) ? "FizzBuzz!" : (i % 5 == 0) ? "Buzz" : (i % 3 == 0) ? "Fizz" : i);
}</lang>
Console Only, Straightforward
<lang Processing>for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) { print("Fizz"); } if (i % 5 == 0) { print("Buzz"); } if (i % 3 != 0 && i % 5 != 0) { print(i); } print("\n");
}</lang>
- Output:
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
Prolog
Maybe not the most conventional way to write this in Prolog. The fizzbuzz predicate uses a higher-order predicate and print_item uses the if-then-else construction. <lang prolog>fizzbuzz :-
foreach(between(1, 100, X), print_item(X)).
print_item(X) :-
( 0 is X mod 15 -> print('FizzBuzz') ; 0 is X mod 3 -> print('Fizz') ; 0 is X mod 5 -> print('Buzz') ; print(X) ), nl.</lang>
More conventional: <lang prolog>fizzbuzz(X) :- 0 is X mod 15, write('FizzBuzz'). fizzbuzz(X) :- 0 is X mod 3, write('Fizz'). fizzbuzz(X) :- 0 is X mod 5, write('Buzz'). fizzbuzz(X) :- write(X).
dofizzbuzz :- foreach(between(1, 100, X), (fizzbuzz(X),nl)).</lang> Clearer: <lang prolog>% N /3? /5? V fizzbuzz(_, yes, yes, 'FizzBuzz'). fizzbuzz(_, yes, no, 'Fizz'). fizzbuzz(_, no, yes, 'Buzz'). fizzbuzz(N, no, no, N).
% Unifies V with 'yes' if D divides evenly into N, 'no' otherwise. divisible_by(N, D, V) :-
( 0 is N mod D -> V = yes ; V = no).
% Print 'Fizz', 'Buzz', 'FizzBuzz' or N as appropriate. fizz_buzz_or_n(N) :-
divisible_by(N, 3, Fizz), divisible_by(N, 5, Buzz), fizzbuzz(N, Fizz, Buzz, FB), format("~p -> ~p~n", [N, FB]).
main :-
foreach(between(1,100, N), fizz_buzz_or_n(N)).</lang>
PureBasic
See FizzBuzz/Basic
Pyret
<lang pyret>is-positive = _ > 0 # equivalent to lam(x): x > 0 end
fun fizzbuzz(n :: Number%(is-positive)) -> String:
doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'. For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.``` ask: | num-modulo(n, 15) == 0 then: "FizzBuzz" | num-modulo(n, 3) == 0 then: "Fizz" | num-modulo(n, 5) == 0 then: "Buzz" | otherwise: num-to-string(n) end
where:
fizzbuzz(1) is "1" fizzbuzz(101) is "101" fizzbuzz(45) is "FizzBuzz" fizzbuzz(33) is "Fizz" fizzbuzz(25) is "Buzz"
end
range(1, 101).map(fizzbuzz).each(print)
</lang>
Python
Python: Simple
<lang python>for i in xrange(1, 101):
if i % 15 == 0: print "FizzBuzz" elif i % 3 == 0: print "Fizz" elif i % 5 == 0: print "Buzz" else: print i</lang>
One liner using string concatenation: <lang python>for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i)</lang>
One liner another code: <lang python>for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or i+1)</lang>
Python: Lazily
You can also create a lazy, unbounded sequence by using generator expressions: <lang python>from itertools import cycle, izip, count, islice
fizzes = cycle([""] * 2 + ["Fizz"]) buzzes = cycle([""] * 4 + ["Buzz"]) both = (f + b for f, b in izip(fizzes, buzzes))
- if the string is "", yield the number
- otherwise yield the string
fizzbuzz = (word or n for word, n in izip(both, count(1)))
- print the first 100
for i in islice(fizzbuzz, 100):
print i</lang>
Q
<lang Q> {$[0=x mod 15;"FizzBuzz";0=x mod 5;"Buzz";0=x mod 3;"Fizz";string x]} each 1+til 15</lang>
Or to print the result: <lang Q> -1 "\n" sv{$[0=x mod 15;"FizzBuzz";0=x mod 5;"Buzz";0=x mod 3;"Fizz";string x]} each 1+til 15;</lang>
R
<lang R>xx <- x <- 1:100 xx[x %% 3 == 0] <- "Fizz" xx[x %% 5 == 0] <- "Buzz" xx[x %% 15 == 0] <- "FizzBuzz" xx</lang>
Or, without directly checking for divisibility by 15: <lang R>xx <- rep("", 100) x <- 1:100 xx[x %% 3 == 0] <- paste0(xx[x %% 3 == 0], "Fizz") xx[x %% 5 == 0] <- paste0(xx[x %% 5 == 0], "Buzz") xx[xx == ""] <- x[xx == ""] xx</lang>
Or, (ab)using the vector recycling rule: <lang R>x <- paste(rep("", 100), c("", "", "Fizz"), c("", "", "", "", "Buzz"), sep="") cat(ifelse(x == "", 1:100, x), "\n")</lang>
Or, with a more straightforward use of ifelse: <lang R>x <- 1:100 ifelse(x %% 15 == 0, 'FizzBuzz',
ifelse(x %% 5 == 0, 'Buzz', ifelse(x %% 3 == 0, 'Fizz', x)))</lang>
Racket
<lang racket>(for ([n (in-range 1 101)])
(displayln (match (gcd n 15) [15 "fizzbuzz"] [3 "fizz"] [5 "buzz"] [_ n])))</lang>
RapidQ
The BASIC solutions work with RapidQ, too. However, here is a bit more esoteric solution using the IIF() function. <lang rapidq>FOR i=1 TO 100
t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "") PRINT IIF(LEN(t$), t$, i)
NEXT i</lang>
Rascal
<lang rascal>import IO;
public void fizzbuzz() {
for(int n <- [1 .. 100]){ fb = ((n % 3 == 0) ? "Fizz" : "") + ((n % 5 == 0) ? "Buzz" : ""); println((fb == "") ?"<n>" : fb); }
}</lang>
Raven
<lang raven>100 each 1 + as n
n 3 mod 0 = if 'Fizz' cat n 5 mod 0 = if 'Buzz' cat dup empty if drop n say</lang>
REALbasic
See FizzBuzz/Basic
REBOL
Shortest implementation: <lang REBOL>repeat i 100 [case/all [i // 3 = 0 [print"fizz"] i // 5 = 0 [print "buzz"] 1 [print i]]]</lang> A long implementation that concatenates strings and includes a proper code header (title, date, etc.) <lang REBOL>REBOL [ Title: "FizzBuzz" Author: oofoe Date: 2009-12-10 URL: http://rosettacode.org/wiki/FizzBuzz ]
- Concatenative. Note use of 'case/all' construct to evaluate all
- conditions. I use 'copy' to allocate a new string each time through
- the loop -- otherwise 'x' would get very long...
repeat i 100 [ x: copy "" case/all [ 0 = mod i 3 [append x "Fizz"] 0 = mod i 5 [append x "Buzz"] "" = x [x: mold i] ] print x ]</lang> Here are two examples by Nick Antonaccio. <lang REBOL>repeat i 100 [
print switch/default 0 compose [ (mod i 15) ["fizzbuzz"] (mod i 3) ["fizz"] (mod i 5) ["buzz"] ][i]
]
- And minimized version
repeat i 100[j:""if 0 = mod i 3[j:"fizz"]if 0 = mod i 5[j: join j"buzz"]if j =""[j: i]print j]</lang> The following is presented as a curiosity only, not as an example of good coding practice: <lang REBOL>m: func [i d] [0 = mod i d] spick: func [t x y][either any [not t "" = t][y][x]] zz: func [i] [rejoin [spick m i 3 "Fizz" "" spick m i 5 "Buzz" ""]] repeat i 100 [print spick z: zz i z i]</lang>
Retro
This is a port of some Forth code. <lang Retro>: fizz? ( s-f ) 3 mod 0 = ;
- buzz? ( s-f ) 5 mod 0 = ;
- num? ( s-f ) dup fizz? swap buzz? or 0 = ;
- ?fizz ( s- ) fizz? [ "Fizz" puts ] ifTrue ;
- ?buzz ( s- ) buzz? [ "Buzz" puts ] ifTrue ;
- ?num ( s- ) num? &putn &drop if ;
- fizzbuzz ( s- ) dup ?fizz dup ?buzz dup ?num space ;
- all ( - ) 100 [ 1+ fizzbuzz ] iter ;</lang>
It's cleaner to use quotes and combinators though: <lang Retro>needs math'
- <fizzbuzz>
[ 15 ^math'divisor? ] [ drop "FizzBuzz" puts ] when [ 3 ^math'divisor? ] [ drop "Fizz" puts ] when [ 5 ^math'divisor? ] [ drop "Buzz" puts ] when putn ;
- fizzbuzz cr 100 [ 1+ <fizzbuzz> space ] iter ;</lang>
REXX
This version's program logic closely mirrors the problem statement:
three IF-THEN
<lang rexx>/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/
/*╔═══════════════════════════════════╗*/ do j=1 to 100; z= j /*║ ║*/ if j//3 ==0 then z= 'Fizz' /*║ The divisors (//) of the IFs ║*/ if j//5 ==0 then z= 'Buzz' /*║ must be in ascending order. ║*/ if j//(3*5)==0 then z= 'FizzBuzz' /*║ ║*/ say right(z, 8) /*╚═══════════════════════════════════╝*/ end /*j*/ /*stick a fork in it, we're all done. */</lang>
output
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
SELECT-WHEN
This version is a different form, but essentially identical to the IF-THEN (above),
but doesn't require the use of a temporary variable to hold/contain the output.
<lang rexx>/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/
/*╔═══════════════════════════════════╗*/ do j=1 to 100 /*║ ║*/ select /*║ ║*/ when j//15==0 then say 'FizzBuzz' /*║ The divisors (//) of the WHENs ║*/ when j//5 ==0 then say ' Buzz' /*║ must be in descending order. ║*/ when j//3 ==0 then say ' Fizz' /*║ ║*/ otherwise say right(j, 8) /*╚═══════════════════════════════════╝*/ end /*select*/ end /*j*/ /*stick a fork in it, we're all done. */</lang>
output is identical to the 1st REXX version.
two IF-THEN
This version lends itself to expansion (such as using Jazz for multiples of 7). <lang rexx>/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/
do j=1 for 100; _= if j//3 ==0 then _=_'Fizz' if j//5 ==0 then _=_'Buzz'
/* if j//7 ==0 then _=_'Jazz' */ /* ◄─── note that this is a comment. */
say right(word(_ j,1),8) end /*j*/ /*stick a fork in it, we're all done. */</lang>
output is identical to the 1st REXX version.
"geek" version
<lang rexx>/*REXX program displays numbers 1 ──► 100 (some transformed) for the FizzBuzz problem.*/
/* [↓] concise, but somewhat obtuse. */ do j=1 for 100 say right(word(word('Fizz', 1+(j//3\==0))word('Buzz', 1+(j//5\==0)) j, 1), 8) end /*j*/ /*stick a fork in it, we're all done. */</lang>
output is identical to the 1st REXX version.
Ring
<lang ring> for n = 1 to 100
if n % 15 = 0 see "" + n + " = " + "FizzBuzz"+ nl but n % 5 = 0 see "" + n + " = " + "Buzz" + nl but n % 3 = 0 see "" + n + " = " + "Fizz" + nl else see "" + n + " = " + n + nl ok
next </lang>
Ruby
<lang ruby>1.upto(100) do |n|
print "Fizz" if a = (n % 3).zero? print "Buzz" if b = (n % 5).zero? print n unless (a || b) puts
end</lang> A bit more straightforward: <lang ruby>(1..100).each do |n|
puts if (n % 15).zero? "FizzBuzz" elsif (n % 5).zero? "Buzz" elsif (n % 3).zero? "Fizz" else n end
end</lang> Enumerable#Lazy and classes:
We can grab the first n fizz/buzz/fizzbuzz numbers in a list with a user defined function (filter_map), starting at the number we desire
i.e, grabbing the first 10 fizz numbers starting from 30, fizz = Fizz.new(30,10) #=> [30, 33, 36, 39, 42, 45, 48, 51, 54, 57] <lang ruby> class Enumerator::Lazy
def filter_map Lazy.new(self) do |holder, *values| result = yield *values holder << result if result end end
end
class Fizz
def initialize(head, tail) @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 3 == 0}.first(tail) end def fizz?(num) search = @list search.include?(num) end def drop(num) list = @list list.delete(num) end def to_a @list.to_a end
end
class Buzz
def initialize(head, tail) @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 5 == 0}.first(tail) end def buzz?(num) search = @list search.include?(num) end def drop(num) list = @list list.delete(num) end def to_a @list.to_a end
end
class FizzBuzz
def initialize(head, tail) @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 15 == 0}.first(tail) end def fizzbuzz?(num) search = @list search.include?(num) end def to_a @list.to_a end def drop(num) list = @list list.delete(num) end
end stopper = 100 @fizz = Fizz.new(1,100) @buzz = Buzz.new(1,100) @fizzbuzz = FizzBuzz.new(1,100) def min(v, n)
if v == 1 puts "Fizz: #{n}" @fizz::drop(n) elsif v == 2 puts "Buzz: #{n}" @buzz::drop(n) else puts "FizzBuzz: #{n}" @fizzbuzz::drop(n) end
end (@fizz.to_a & @fizzbuzz.to_a).map{|d| @fizz::drop(d)} (@buzz.to_a & @fizzbuzz.to_a).map{|d| @buzz::drop(d)} while @fizz.to_a.min < stopper or @buzz.to_a.min < stopper or @fizzbuzz.to_a.min < stopper
f, b, fb = @fizz.to_a.min, @buzz.to_a.min, @fizzbuzz.to_a.min min(1,f) if f < fb and f < b min(2,b) if b < f and b < fb min(0,fb) if fb < b and fb < f
end</lang>
An example using string interpolation: <lang ruby>(1..100).each do |n|
v = "#{"Fizz" if n % 3 == 0}#{"Buzz" if n % 5 == 0}" puts v.empty? ? n : v
end</lang>
Interpolation inspired one-liner: <lang ruby>1.upto(100) { |n| puts "#{'Fizz' if n % 3 == 0}#{'Buzz' if n % 5 == 0}#{n if n % 3 != 0 && n % 5 != 0}" }</lang>
An example using append: <lang ruby>1.upto 100 do |n|
r = r << 'Fizz' if n % 3 == 0 r << 'Buzz' if n % 5 == 0 r << n.to_s if r.empty? puts r
end</lang>
Yet another solution: <lang>1.upto(100) { |i| puts "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/] || i }</lang>
Yet another solution: <lang ruby>1.upto(100){|i|puts'FizzBuzz '[n=i**4%-15,n+13]||i}</lang>
Used Enumerable#cycle: <lang ruby>f = [nil, nil, :Fizz].cycle b = [nil, nil, nil, nil, :Buzz].cycle (1..100).each do |i|
puts "#{f.next}#{b.next}"[/.+/] || i
end</lang>
After beforehand preparing the Array which put the number from 1 to 100, it processes. <lang ruby>seq = *0..100 {Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}} puts seq.drop(1)</lang>
Monkeypatch example: <lang ruby>class Integer
def fizzbuzz v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}" v.empty? ? self : v end
end
puts *(1..100).map(&:fizzbuzz)</lang>
Without mutable variables or inline printing. <lang ruby>fizzbuzz = ->(i) do
(i%15).zero? and next "FizzBuzz" (i%3).zero? and next "Fizz" (i%5).zero? and next "Buzz" i
end
puts (1..100).map(&fizzbuzz).join("\n")</lang> Jump anywhere#Ruby has a worse example of FizzBuzz, using a continuation!
Ruby with RSpec
This is a solution to FizzBuzz using Test-Driven Development (In this case, with Ruby and RSpec). You will need to set up the correct file structure first, with /lib and /spec directories in your root.
Your spec/fizzbuzz_spec.rb file should like this:
<lang ruby> require 'fizzbuzz'
describe 'FizzBuzz' do
context 'knows that a number is divisible by' do it '3' do expect(is_divisible_by_three?(3)).to be_true end it '5' do expect(is_divisible_by_five?(5)).to be_true end it '15' do expect(is_divisible_by_fifteen?(15)).to be_true end end context 'knows that a number is not divisible by' do it '3' do expect(is_divisible_by_three?(1)).not_to be_true end it '5' do expect(is_divisible_by_five?(1)).not_to be_true end it '15' do expect(is_divisible_by_fifteen?(1)).not_to be_true end end context 'while playing the game it returns' do it 'the number' do expect(fizzbuzz(1)).to eq 1 end it 'Fizz' do expect(fizzbuzz(3)).to eq 'Fizz' end it 'Buzz' do expect(fizzbuzz(5)).to eq 'Buzz' end it 'FizzBuzz' do expect(fizzbuzz(15)).to eq 'FizzBuzz' end
end
</lang>
There are many ways to get these tests to pass. Here is an example solution of what your lib/fizzbuzz.rb file could look like:
<lang ruby> def fizzbuzz(number)
return 'FizzBuzz' if is_divisible_by_fifteen?(number) return 'Buzz' if is_divisible_by_five?(number) return 'Fizz' if is_divisible_by_three?(number) number
end
def is_divisible_by_three?(number)
is_divisible_by(number, 3)
end
def is_divisible_by_five?(number)
is_divisible_by(number, 5)
end
def is_divisible_by_fifteen?(number)
is_divisible_by(number, 15)
end
def is_divisible_by_(number, divisor)
number % divisor == 0
end
</lang>
When writing Test Driven code, it's important to remember that you should use the Red, Green, Refactor cycle. Simply writing each of these code snippets independently would go against everything TDD is about. Here is a good video that takes you through the process of writing this FizzBuzz implementation using Ruby & RSpec.
Run BASIC
See FizzBuzz/Basic
Rust
<lang rust>use std::borrow::Cow; fn main() {
for i in 1..101 { let word: Cow<_> = match (i % 3, i % 5) { (0,0) => "FizzBuzz".into(), (0,_) => "Fizz".into(), (_, 0) => "Buzz".into(), _ => i.to_string().into(), }; println!("{}", word); }
}</lang>
Or the ultimate optimized version with hardcoded output, no standard library or main function, and direct assembly syscalls to write to stdout. <lang rust> #![no_std]
- ![feature(asm, lang_items, libc, no_std, start)]
extern crate libc;
const LEN: usize = 413; static OUT: [u8; LEN] = *b"\
1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n\ 16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n\ 31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n\ 46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n\ 61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n\ 76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n\ 91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n";
- [start]
fn start(_argc: isize, _argv: *const *const u8) -> isize {
unsafe { asm!( " mov $$1, %rax mov $$1, %rdi mov $0, %rsi mov $1, %rdx syscall " : : "r" (&OUT[0]) "r" (LEN) : "rax", "rdi", "rsi", "rdx" : ); } 0
}
- [lang = "eh_personality"] extern fn eh_personality() {}
- [lang = "panic_fmt"] extern fn panic_fmt() {}</lang>
Salmon
<lang Salmon>iterate (x; [1...100])
((x % 15 == 0) ? "FizzBuzz" : ((x % 3 == 0) ? "Fizz" : ((x % 5 == 0) ? "Buzz" : x)))!;</lang>
or <lang Salmon>iterate (x; [1...100])
{ if (x % 15 == 0) "FizzBuzz"! else if (x % 3 == 0) "Fizz"! else if (x % 5 == 0) "Buzz"! else x!; };</lang>
Sather
<lang sather>class MAIN is
main is loop i ::= 1.upto!(100); s:STR := ""; if i % 3 = 0 then s := "Fizz"; end; if i % 5 = 0 then s := s + "Buzz"; end; if s.length > 0 then #OUT + s + "\n"; else #OUT + i + "\n"; end; end; end;
end;</lang>
Scala
Idiomatic scala code
<lang scala>object FizzBuzz extends App {
1 to 100 foreach { n => println((n % 3, n % 5) match { case (0, 0) => "FizzBuzz" case (0, _) => "Fizz" case (_, 0) => "Buzz" case _ => n }) }
}</lang>
Geeky over-generalized solution ☺
<lang scala>def replaceMultiples(x: Int, rs: (Int, String)*): Either[Int, String] =
rs map { case (n, s) => Either cond(x % n == 0, s, x)} reduceLeft ((a, b) => a fold(_ => b, s => b fold(_ => a, t => Right(s + t))))
def fizzbuzz = replaceMultiples(_: Int, 3 -> "Fizz", 5 -> "Buzz") fold(_.toString, identity)
1 to 100 map fizzbuzz foreach println</lang>
By a two-liners geek
<lang scala>def f(n: Int, div: Int, met: String, notMet: String): String = if (n % div == 0) met else notMet for (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString))))</lang>
One-liner geek
<lang scala>for (i <- 1 to 100) println(Seq(15 -> "FizzBuzz", 3 -> "Fizz", 5 -> "Buzz").find(i % _._1 == 0).map(_._2).getOrElse(i))</lang>
Functional Scala
<lang scala>def fizzbuzz(l: List[String], n: Int, s: String) = if (l.head.toInt % n == 0) l :+ s else l def fizz(l: List[String]) = fizzbuzz(l, 3, "Fizz") def buzz(l: List[String]) = fizzbuzz(l, 5, "Buzz") def headOrTail(l: List[String]) = if (l.tail.size == 0) l.head else l.tail.mkString Stream.from(1).take(100).map(n => List(n.toString)).map(fizz).map(buzz).map(headOrTail).foreach(println)</lang>
Scheme
<lang scheme>(do ((i 1 (+ i 1)))
((> i 100)) (display (cond ((= 0 (modulo i 15)) "FizzBuzz") ((= 0 (modulo i 3)) "Fizz") ((= 0 (modulo i 5)) "Buzz") (else i))) (newline))</lang>
Using a recursive procedure.
<lang scheme>(define (fizzbuzz x y)
(println (cond (( = (modulo x 15) 0 ) "FizzBuzz") (( = (modulo x 3) 0 ) "Fizz") (( = (modulo x 5) 0 ) "Buzz") (else x)))
(if (< x y) (fizzbuzz (+ x 1) y)))
(fizzbuzz 1 100)</lang>
Sed
<lang sed>#n
- doesn't work if there's no input
- initialize counters (0 = empty) and value
s/.*/ 0/
- loop
- increment counters, set carry
s/^\(a*\) \(b*\) \([0-9][0-9]*\)/\1a \2b \3@/
- propagate carry
- carry
s/ @/ 1/ s/9@/@0/ s/8@/9/ s/7@/8/ s/6@/7/ s/5@/6/ s/4@/5/ s/3@/4/ s/2@/3/ s/1@/2/ s/0@/1/ /@/b carry
- save state
h
- handle factors
s/aaa/Fizz/ s/bbbbb/Buzz/
- strip value if any factor
/z/s/[0-9]//g
- strip counters and spaces
s/[ab ]//g
- output
p
- restore state
g
- roll over counters
s/aaa// s/bbbbb//
- loop until value = 100
/100/q b loop</lang>
Using seq:
<lang sed> seq 1 100 | sed -r '3~3 s/[0-9]*/Fizz/; 5~5 s/[0-9]*$/Buzz/' </lang>
Seed7
<lang seed7>$ include "seed7_05.s7i";
const proc: main is func
local var integer: number is 0; begin for number range 1 to 100 do if number rem 15 = 0 then writeln("FizzBuzz"); elsif number rem 5 = 0 then writeln("Buzz"); elsif number rem 3 = 0 then writeln("Fizz"); else writeln(number); end if; end for; end func;</lang>
SequenceL
<lang sequencel>import <Utilities/Conversion.sl>; import <Utilities/Sequence.sl>;
main(args(2)) := let result[i] := "FizzBuzz" when i mod 3 = 0 and i mod 5 = 0 else "Fizz" when i mod 3 = 0 else "Buzz" when i mod 5 = 0 else intToString(i) foreach i within 1 ... 100; in delimit(result, '\n');</lang>
Shen
<lang Shen>(define fizzbuzz
101 -> (nl) N -> (let divisible-by? (/. A B (integer? (/ A B))) (cases (divisible-by? N 15) (do (output "Fizzbuzz!~%") (fizzbuzz (+ N 1))) (divisible-by? N 3) (do (output "Fizz!~%") (fizzbuzz (+ N 1))) (divisible-by? N 5) (do (output "Buzz!~%") (fizzbuzz (+ N 1))) true (do (output (str N)) (nl) (fizzbuzz (+ N 1))))))
(fizzbuzz 1)</lang>
Sidef
<lang ruby>{ |i|
if (i %% 3) { print "Fizz"; i %% 5 && print "Buzz"; print "\n"; } elsif (i %% 5) { say "Buzz" } else { say i };
} * 100;</lang>
Shorter solution: <lang ruby>{|i|say "#{<Fizz>[i%3]}#{<Buzz>[i%5]}"||i}*100;</lang>
Slate
<lang slate>n@(Integer traits) fizzbuzz [
output ::= ((n \\ 3) isZero ifTrue: ['Fizz'] ifFalse: []) ; ((n \\ 5) isZero ifTrue: ['Buzz'] ifFalse: []). output isEmpty ifTrue: [n printString] ifFalse: [output]
]. 1 to: 100 do: [| :i | inform: i fizzbuzz]</lang>
Smalltalk
Since only GNU Smalltalk supports file-based programming, we'll be using its syntax. <lang smalltalk>Integer extend [
fizzbuzz [ | fb | fb := '%<Fizz|>1%<Buzz|>2' % { self \\ 3 == 0. self \\ 5 == 0 }. ^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ] ]
] 1 to: 100 do: [ :i | i fizzbuzz displayNl ]</lang> A Squeak/Pharo example using the Transcript window: <lang smalltalk>(1 to: 100) do: [:n | ((n \\ 3)*(n \\ 5)) isZero
ifFalse: [Transcript show: n].
(n \\ 3) isZero ifTrue: [Transcript show: 'Fizz']. (n \\ 5) isZero ifTrue: [Transcript show: 'Buzz']. Transcript cr.]</lang> The Squeak/Pharo examples below present possibilities using the powerful classes available. In this example, the dictionary can have as keys pairs of booleans and in the interaction the several boolean patterns select the string to be printed or if the pattern is not found the number itself is printed. <lang smalltalk>fizzbuzz := Dictionary with: #(true true)->'FizzBuzz'
with: #(true false)->'Fizz' with: #(false true)->'Buzz'.
1 to: 100 do: [ :i | Transcript show:
(fizzbuzz at: {i isDivisibleBy: 3. i isDivisibleBy: 5}
ifAbsent: [ i ]); cr]</lang> Smalltalk does not have a case-select construct, but a similar effect can be attained using a collection and the #includes: method: <lang smalltalk>1 to: 100 do: [:n | |r| r := n rem: 15. Transcript show: (r isZero ifTrue:['fizzbuzz'] ifFalse: [(#(3 6 9 12) includes: r) ifTrue:['fizz'] ifFalse:[((#(5 10) includes: r)) ifTrue:['buzz'] ifFalse:[n]]]); cr].</lang> If the construction of the whole collection is done beforehand, Smalltalk provides a straightforward way of doing because collections can be heterogeneous (may contain any object): <lang smalltalk>fbz := (1 to: 100) asOrderedCollection.
3 to: 100 by: 3 do: [:i | fbz at: i put: 'Fizz']. 5 to: 100 by: 5 do: [:i | fbz at: i put: 'Buzz'].
15 to: 100 by: 15 do: [:i | fbz at: i put: 'FizzBuzz']. fbz do: [:i | Transcript show: i; cr].</lang> The approach building a dynamic string can be done as well: <lang smalltalk>1 to: 100 do: [:i | |fb s| fb := {i isDivisibleBy: 3. i isDivisibleBy: 5. nil}. fb at: 3 put: (fb first | fb second) not. s := '<1?Fizz:><2?Buzz:><3?{1}:>' format: {i printString}. Transcript show: (s expandMacrosWithArguments: fb); cr].</lang>
SNOBOL4
Merely posting a solution by Daniel Lyons <lang snobol4> I = 1 LOOP FIZZBUZZ = ""
EQ(REMDR(I, 3), 0) :F(TRY_5) FIZZBUZZ = FIZZBUZZ "FIZZ"
TRY_5 EQ(REMDR(I, 5), 0) :F(DO_NUM)
FIZZBUZZ = FIZZBUZZ "BUZZ"
DO_NUM IDENT(FIZZBUZZ, "") :F(SHOW)
FIZZBUZZ = I
SHOW OUTPUT = FIZZBUZZ
I = I + 1 LE(I, 100) :S(LOOP)
END</lang>
SNUSP
See FizzBuzz/EsoLang
SQL
Oracle SQL
<lang sql>SELECT CASE
WHEN MOD(level,15)=0 THEN 'FizzBuzz' WHEN MOD(level,3)=0 THEN 'Fizz' WHEN MOD(level,5)=0 THEN 'Buzz' ELSE TO_CHAR(level) END FizzBuzz FROM dual CONNECT BY LEVEL <= 100;</lang>
Or using Oracle's DECODE and NVL: <lang sql>SELECT nvl(decode(MOD(level,3),0,'Fizz')||decode(MOD(level,5),0,'Buzz'),level) FROM dual CONNECT BY level<=100;</lang>
PostgreSQL specific
<lang sql>SELECT i, fizzbuzz
FROM (SELECT i, CASE WHEN i % 15 = 0 THEN 'FizzBuzz' WHEN i % 5 = 0 THEN 'Buzz' WHEN i % 3 = 0 THEN 'Fizz' ELSE NULL END AS fizzbuzz FROM generate_series(1,100) AS i) AS fb WHERE fizzbuzz IS NOT NULL;</lang>
Using Generate_Series and tables only: <lang sql>SELECT COALESCE(FIZZ || BUZZ, FIZZ, BUZZ, OUTPUT) AS FIZZBUZZ FROM (SELECT GENERATE_SERIES AS FULL_SERIES, TO_CHAR(GENERATE_SERIES,'99') AS OUTPUT FROM GENERATE_SERIES(1,100)) F LEFT JOIN (SELECT TEXT 'Fizz' AS FIZZ, GENERATE_SERIES AS FIZZ_SERIES FROM GENERATE_SERIES(0,100,3)) FIZZ ON FIZZ.FIZZ_SERIES = F.FULL_SERIES LEFT JOIN (SELECT TEXT 'Buzz' AS BUZZ, GENERATE_SERIES AS BUZZ_SERIES FROM GENERATE_SERIES(0,100,5)) BUZZ ON BUZZ.BUZZ_SERIES = F.FULL_SERIES;</lang>
Recursive Common Table Expressions (MSSQL 2005+)
<lang sql>WITH nums (n, fizzbuzz ) AS ( SELECT 1, CONVERT(nvarchar, 1) UNION ALL SELECT (n + 1) as n1, CASE WHEN (n + 1) % 15 = 0 THEN 'FizzBuzz' WHEN (n + 1) % 3 = 0 THEN 'Fizz' WHEN (n + 1) % 5 = 0 THEN 'Buzz' ELSE CONVERT(nvarchar, (n + 1)) END FROM nums WHERE n < 100 ) SELECT n, fizzbuzz FROM nums ORDER BY n ASC OPTION ( MAXRECURSION 100 )</lang>
Generic SQL using a join
This should work in most RDBMSs, but you may need to change MOD(i,divisor) to i % divisor. <lang SQL>-- Load some numbers CREATE TABLE numbers(i INTEGER); INSERT INTO numbers VALUES(1); INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; INSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers; -- Define the fizzes and buzzes CREATE TABLE fizzbuzz (message VARCHAR(8), divisor INTEGER); INSERT INTO fizzbuzz VALUES('fizz', 3); INSERT INTO fizzbuzz VALUES('buzz', 5); INSERT INTO fizzbuzz VALUES('fizzbuzz', 15); -- Play fizzbuzz SELECT COALESCE(max(message),CAST(i AS VARCHAR(99))) as result FROM numbers LEFT OUTER JOIN fizzbuzz ON MOD(i,divisor) = 0 GROUP BY i HAVING i <= 100 ORDER BY i; -- Tidy up DROP TABLE fizzbuzz; DROP TABLE numbers;</lang>
Squirrel
<lang javascript>function Fizzbuzz(n) {
for (local i = 1; i <= n; i += 1) { if (i % 15 == 0) print ("FizzBuzz\n") else if (i % 5 == 0) print ("Buzz\n") else if (i % 3 == 0) print ("Fizz\n") else { print (i + "\n") } }
} Fizzbuzz(100);</lang>
Swift
<lang swift>for i in 1...100 {
switch (i % 3, i % 5) { case (0, 0): print("FizzBuzz") case (0, _): print("Fizz") case (_, 0): print("Buzz") default: print(i) }
}</lang>
Symsyn
<lang symsyn> | FizzBuzz
1 I if I LE 100 mod I 3 X mod I 5 Y if X EQ 0 'FIZZ' $S if Y EQ 0 + 'BUZZ' $S endif else if Y EQ 0 'BUZZ' $S else ~ I $S endif endif $S [] + I goif endif
</lang>
Tcl
<lang tcl>proc fizzbuzz {n {m1 3} {m2 5}} {
for {set i 1} {$i <= $n} {incr i} { set ans "" if {$i % $m1 == 0} {append ans Fizz} if {$i % $m2 == 0} {append ans Buzz} puts [expr {$ans eq "" ? $i : $ans}] }
} fizzbuzz 100</lang> The following example shows Tcl's substitution mechanism that allows to concatenate the results of two successive commands into a string: <lang tcl>while {[incr i] < 101} {
set fb [if {$i % 3 == 0} {list Fizz}][if {$i % 5 == 0} {list Buzz}] if {$fb ne ""} {puts $fb} {puts $i}
}</lang> This version uses list rotation, so avoiding an explicit mod operation: <lang tcl>set f [lrepeat 5 "Fizz" {$i} {$i}] foreach i {5 10} {lset f $i "Buzz"};lset f 0 "FizzBuzz" for {set i 1} {$i <= 100} {incr i} {
puts [subst [lindex [set f [list {*}[lassign $f ff] $ff]] 0]]
}</lang>
TI-83 BASIC
See FizzBuzz/Basic
Turing
<lang Turing>setscreen("nocursor,noecho")
for i : 1 .. 100
if i mod 15 = 0 then put "Fizzbuzz" .. elsif i mod 5 = 0 then put "Buzz" .. elsif i mod 3 = 0 then put "Fizz" .. else put i .. end if
end for</lang>
TUSCRIPT
<lang tuscript>$$ MODE TUSCRIPT LOOP n=1,100 mod=MOD (n,15) SELECT mod CASE 0 PRINT n," FizzBuzz" CASE 3,6,9,12 PRINT n," Fizz" CASE 5,10 PRINT n," Buzz" DEFAULT PRINT n ENDSELECT ENDLOOP</lang>
TXR
<lang shell>$ txr -p "(mapcar (op if @1 @1 @2) (repeat '(nil nil fizz nil buzz fizz nil nil fizz buzz nil fizz nil nil fizzbuzz)) (range 1 100))"</lang>
UNIX Shell
This solution should work with any Bourne-compatible shell: <lang bash>i=1 while expr $i '<=' 100 >/dev/null; do w=false expr $i % 3 = 0 >/dev/null && { printf Fizz; w=true; } expr $i % 5 = 0 >/dev/null && { printf Buzz; w=true; } if $w; then echo; else echo $i; fi i=`expr $i + 1` done</lang>
Versions for specific shells
The other solutions work with fewer shells.
The next solution requires $(( ))
arithmetic expansion,
which is in every POSIX shell; but it also requires the seq(1) command,
which is not part of some systems.
(If your system misses seq(1), but it has BSD jot(1), then change `seq 1 100` to `jot 100`.)
<lang bash>for n in `seq 1 100`; do
if [ $((n % 15)) = 0 ]; then echo FizzBuzz elif [ $((n % 3)) = 0 ]; then echo Fizz elif [ $((n % 5)) = 0 ]; then echo Buzz else echo $n fi
done</lang>
The next solution requires the (( ))
command from the Korn Shell.
<lang bash>NUM=1 until ((NUM == 101)) ; do
if ((NUM % 15 == 0)) ; then echo FizzBuzz elif ((NUM % 3 == 0)) ; then echo Fizz elif ((NUM % 5 == 0)) ; then echo Buzz else echo "$NUM" fi ((NUM = NUM + 1))
done</lang>
A version using concatenation:
<lang bash>for ((n=1; n<=100; n++)) do
fb= [ $(( n % 3 )) -eq 0 ] && fb="${fb}Fizz" [ $(( n % 5 )) -eq 0 ] && fb="${fb}Buzz" [ -n "${fb}" ] && echo "${fb}" || echo "$n"
done</lang>
A version using some of the insane overkill of Bash 4:
<lang bash>command_not_found_handle () {
local Fizz=3 Buzz=5 [ $(( $2 % $1 )) -eq 0 ] && echo -n $1 && [ ${!1} -eq 3 ]
}
for i in {1..100} do
Fizz $i && ! Buzz $i || echo -n $i echo
done</lang>
Bash one-liner: <lang bash>for i in {1..100};do ((($i%15==0))&& echo FizzBuzz)||((($i%5==0))&& echo Buzz;)||((($i%3==0))&& echo Fizz;)||echo $i;done</lang>
C Shell
<lang csh>@ n = 1 while ( $n <= 100 )
if ($n % 15 == 0) then echo FizzBuzz else if ($n % 5 == 0) then echo Buzz else if ($n % 3 == 0) then echo Fizz else echo $n endif @ n += 1
end</lang>
Ursa
<lang ursa>#
- fizzbuzz
decl int i for (set i 1) (< i 101) (inc i)
if (= (mod i 3) 0) out "fizz" console end if if (= (mod i 5) 0) out "buzz" console end if if (not (or (= (mod i 3) 0) (= (mod i 5) 0))) out i console end if out endl console
end for</lang>
Ursala
<lang Ursala>#import std
- import nat
fizzbuzz = ^T(&&'Fizz'! not remainder\3,&&'Buzz'! not remainder\5)|| ~&h+ %nP
- show+
main = fizzbuzz*t iota 101</lang>
V
<lang v>[fizzbuzz
1 [>=] [ [[15 % zero?] ['fizzbuzz' puts] [5 % zero?] ['buzz' puts] [3 % zero?] ['fizz' puts] [true] [dup puts] ] when succ ] while]. |100 fizzbuzz</lang>
Second try
(a compiler for fizzbuzz)
define a command that will generate a sequence <lang v>[seq [] swap dup [zero? not] [rolldown [dup] dip cons rollup pred] while pop pop].</lang> create a quote that will return a quote that returns a quote if its argument is an integer (A HOF) <lang v>[check [N X F : [[integer?] [[X % zero?] [N F cons] if] if]] view].</lang> Create a quote that will make sure that the above quote is applied correctly if given (Number Function) as arguments. <lang v>[func [[N F] : [dup N F check i] ] view map].</lang> And apply it <lang v>100 seq [
[15 [pop 'fizzbuzz' puts]] [5 [pop 'buzz' puts]] [3 [pop 'fizz' puts]] [1 [puts]]] [func dup] step [i true] map pop</lang>
the first one is much better :)
Vala
<lang vala>int main() { for(int i = 1; i < 100; i++) { if(i % 3 == 0) stdout.printf("Fizz"); if(i % 5 == 0) stdout.printf("Buzz"); if(i % 3 != 0 && i % 5 != 0) stdout.printf("%d", i); stdout.printf("\n"); } return 0; }</lang>
VBScript
<lang VBScript>For i = 1 To 100 If i Mod 15 = 0 Then WScript.Echo "FizzBuzz" ElseIf i Mod 5 = 0 Then WScript.Echo "Buzz" ElseIf i Mod 3 = 0 Then WScript.Echo "Fizz" Else WScript.Echo i End If Next</lang>
An Alternative
<lang VBScript>With WScript.StdOut For i = 1 To 100 If i Mod 3 = 0 Then .Write "Fizz" If i Mod 5 = 0 Then .Write "Buzz" If .Column = 1 Then .WriteLine i Else .WriteLine "" Next End With</lang>
Vim Script
<lang vim>for i in range(1, 100)
if i % 15 == 0 echo "FizzBuzz" elseif i % 5 == 0 echo "Buzz" elseif i % 3 == 0 echo "Fizz" else echo i endif
endfor</lang>
Visual Basic .NET
See FizzBuzz/Basic
Visual Prolog
<lang> implement main
open core, console
class predicates
fizzbuzz : (integer) -> string procedure (i).
clauses
fizzbuzz(X) = S :- X mod 15 = 0, S = "FizzBuzz", !. fizzbuzz(X) = S :- X mod 5 = 0, S = "Buzz", !. fizzbuzz(X) = S :- X mod 3 = 0, S = "Fizz", !. fizzbuzz(X) = S :- S = toString(X).
run() :- foreach X = std::fromTo(1,100) do write(fizzbuzz(X)), write("\n") end foreach, succeed.
end implement main
goal
console::runUtf8(main::run).
</lang>
Wart
<lang wart>for i 1 (i <= 100) ++i
prn (if (divides i 15) "FizzBuzz" (divides i 3) "Fizz" (divides i 5) "Buzz" :else i)</lang>
Whitespace
See FizzBuzz/EsoLang
Wortel
<lang wortel>@each &x!console.log x !*&x?{%%x 15 "FizzBuzz" %%x 5 "Buzz" %%x 3 "Fizz" x} @to 100</lang>
XMIDAS
<lang XMIDAS>startmacro
loop 100 count calc/quiet three ^count 3 modulo calc/quiet five ^count 5 modulo if ^three eq 0 and ^five eq 0 say "fizzbuzz" elseif ^three eq 0 say "fizz" elseif ^five eq 0 say "buzz" else say ^count endif endloop
endmacro</lang>
XLISP
<lang lisp>(defun fizzbuzz ()
(defun fizzb (x y) (display (cond ((= (mod x 3) (mod x 5) 0) "FizzBuzz") ((= (mod x 3) 0) "Fizz") ((= (mod x 5) 0) "Buzz") (t x))) (newline) (if (< x y) (fizzb (+ x 1) y))) (fizzb 1 100))
(fizzbuzz)</lang>
XPL0
<lang XPL0>code CrLf=9, IntOut=11, Text=12; int N; [for N:= 1 to 100 do
[if rem(N/3)=0 then Text(0,"Fizz"); if rem(N/5)=0 then Text(0,"Buzz") else if rem(N/3)#0 then IntOut(0,N); CrLf(0); ];
]</lang>
- Output:
1 2 Fizz 4 Buzz Fizz 7 ... 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
XPath 2.0
<lang XPath>for $n in 1 to 100 return
concat('fizz'[not($n mod 3)], 'buzz'[not($n mod 5)], $n[$n mod 15 = (1,2,4,7,8,11,13,14)])</lang>
...or alternatively... <lang XPath>for $n in 1 to 100 return
($n, 'Fizz', 'Buzz', 'FizzBuzz')[number(($n mod 3) = 0) + number(($n mod 5) = 0)*2 + 1]</lang>
XSLT
XSLT 1.0
<lang xml><?xml version="1.0" encoding="utf-8" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="text" encoding="utf-8"/>
<xsl:template name="fizzbuzz-single"> <xsl:param name="n"/>
<xsl:variable name="s"> <xsl:if test="$n mod 3 = 0">Fizz</xsl:if> <xsl:if test="$n mod 5 = 0">Buzz</xsl:if> </xsl:variable>
<xsl:value-of select="$s"/> <xsl:if test="$s = "> <xsl:value-of select="$n"/> </xsl:if>
<xsl:value-of select="' '"/> </xsl:template>
<xsl:template name="fizzbuzz-range"> <xsl:param name="startAt" select="1"/> <xsl:param name="endAt" select="$startAt + 99"/>
<xsl:if test="$startAt <= $endAt">
<xsl:call-template name="fizzbuzz-single">
<xsl:with-param name="n" select="$startAt"/>
</xsl:call-template>
<xsl:call-template name="fizzbuzz-range"> <xsl:with-param name="startAt" select="$startAt + 1"/> <xsl:with-param name="endAt" select="$endAt"/> </xsl:call-template> </xsl:if> </xsl:template>
<xsl:template match="/"> <xsl:call-template name="fizzbuzz-range"/> </xsl:template> </xsl:stylesheet></lang>
XSLT 1.0 With EXSLT
<lang xml><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" exclude-result-prefixes="xsl exsl">
<xsl:output method="text"/>
<xsl:template name="FizzBuzz" match="/">
<xsl:param name="n" select="1" /> <xsl:variable name="_"> <_><xsl:value-of select="$n" /></_> </xsl:variable> <xsl:apply-templates select="exsl:node-set($_)/_" /> <xsl:if test="$n < 100"> <xsl:call-template name="FizzBuzz"> <xsl:with-param name="n" select="$n + 1" /> </xsl:call-template> </xsl:if>
</xsl:template>
<xsl:template match="_[. mod 3 = 0]">Fizz </xsl:template>
<xsl:template match="_[. mod 5 = 0]">Buzz </xsl:template>
<xsl:template match="_[. mod 15 = 0]" priority="1">FizzBuzz </xsl:template>
<xsl:template match="_">
<xsl:value-of select="concat(.,' ')" />
</xsl:template>
</xsl:stylesheet></lang>
XSLT 2.0
<lang xml><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/>
<xsl:template match="/">
<xsl:value-of separator=" " select=" for $n in 1 to 100 return concat('fizz'[not($n mod 3)], 'buzz'[not($n mod 5)], $n[$n mod 15 = (1,2,4,7,8,11,13,14)])"/>
</xsl:template>
</xsl:stylesheet></lang>
Yorick
Iterative solution
<lang yorick>for(i = 1; i <= 100; i++) {
if(i % 3 == 0) write, format="%s", "Fizz"; if(i % 5 == 0) write, format="%s", "Buzz"; if(i % 3 && i % 5) write, format="%d", i; write, "";
}</lang>
Vectorized solution
<lang yorick>output = swrite(format="%d", indgen(100)); output(3::3) = "Fizz"; output(5::5) = "Buzz"; output(15::15) = "FizzBuzz"; write, format="%s\n", output;</lang>
Z80 Assembly
zkl
<lang zkl>foreach n in ([1..100]) {
if(n % 3 == 0) print("Fizz"); if(not (n%5)) "Buzz".print(); if(n%3 and n%5) print(n); println();
}</lang> Or, using infinite lazy sequences: <lang zkl>fcn f(a,b,c){ a+b and a+b or c } Walker.cycle("","","Fizz").zipWith(f,Walker.cycle("","","","","Buzz"),[1..])
.walk(100).concat("\n").println();</lang>
More of the same: <lang zkl>Walker.cycle(0,0,"Fizz",0,"Buzz","Fizz",0,0,"Fizz","Buzz",0,"Fizz",0,0,"FizzBuzz")
.zipWith(fcn(a,b){ a or b },[1..]).walk(100).concat("\n").println();</lang>
- Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ...
ZX Spectrum Basic
<lang zxbasic>10 DEF FN m(a,b)=a-INT (a/b)*b 20 FOR a=1 TO 100 30 LET o$="" 40 IF FN m(a,3)=0 THEN LET o$="Fizz" 50 IF FN m(a,5)=0 THEN LET o$=o$+"Buzz" 60 IF o$="" THEN LET o$=STR$ a 70 PRINT o$ 80 NEXT a</lang>
- Programming Tasks
- Classic CS problems and programs
- Iteration
- Recursion
- Simple
- 360 Assembly
- 6502 Assembly
- 68000 Assembly
- 8086 Assembly
- 8th
- ABAP
- ACL2
- ActionScript
- Ada
- ALGOL 68
- ALGOL W
- AntLang
- APEX
- APL
- AppleScript
- Applesoft BASIC
- Arbre
- Arc
- AutoHotkey
- AutoIt
- AWK
- Axe
- Babel
- Bash
- BASIC
- Batch File
- BBC BASIC
- Bc
- Beeswax
- Befunge
- Boo
- Bracmat
- Brat
- Brainf***
- C
- C++
- C sharp
- Casio BASIC
- Cduce
- Ceylon
- Chef
- Clay
- Clipper
- CLIPS
- Clojure
- CMake
- COBOL
- Coco
- CoffeeScript
- ColdFusion
- Common Lisp
- Crystal
- Cubescript
- Chapel
- D
- Dart
- Dc
- Delphi
- Déjà Vu
- DeviousYarn
- DWScript
- E
- Eiffel
- ECL
- Eero
- Ela
- Elixir
- Elm
- Erlang
- ERRE
- Euphoria
- Factor
- F Sharp
- Falcon
- FALSE
- Fantom
- FBSL
- Forth
- Fortran
- Frege
- Frink
- FutureBasic
- GAP
- GFA Basic
- Go
- Gosu
- Groovy
- GW-BASIC
- Haskell
- HicEst
- Hoon
- Hy
- Icon
- Unicon
- Idris
- Inform 6
- Inform 7
- Io
- Ioke
- Iptscrae
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- K
- Kamailio Script
- Kaya
- Klong
- Kotlin
- LabVIEW
- Lasso
- LaTeX
- Ifthen
- Intcalc
- Liberty BASIC
- LiveCode
- LiveScript
- Lobster
- Logo
- LOLCODE
- LSE
- Lua
- Luck
- M4
- Make
- Jot
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Maxima
- MAXScript
- MEL
- Mercury
- Metafont
- Mirah
- ML
- Standard ML
- MLite
- MMIX
- Modula-3
- Monte
- MoonScript
- MUMPS
- Neko
- Nemerle
- NetRexx
- NewtonScript
- Nickle
- NewLISP
- Nim
- Oberon-2
- Objeck
- Objective-C
- OCaml
- Octave
- Oforth
- OOC
- Order
- Oz
- PARI/GP
- Pascal
- Peloton
- Perl
- Perl 6
- Phix
- PHL
- PHP
- PicoLisp
- Pike
- PIR
- PL/I
- Pony
- Pop11
- PL/SQL
- PostScript
- Potion
- PowerShell
- Processing
- Prolog
- PureBasic
- Pyret
- Python
- Q
- R
- Racket
- RapidQ
- Rascal
- Raven
- REALbasic
- REBOL
- Retro
- REXX
- Ring
- Ruby
- Ruby with RSpec
- Run BASIC
- Rust
- Salmon
- Sather
- Scala
- Scheme
- Sed
- Seed7
- SequenceL
- Shen
- Sidef
- Slate
- Smalltalk
- SNOBOL4
- SNUSP
- SQL
- Squirrel
- Swift
- Symsyn
- Tcl
- TI-83 BASIC
- Turing
- TUSCRIPT
- TXR
- UNIX Shell
- C Shell
- Ursa
- Ursala
- V
- Vala
- VBScript
- Vim Script
- Visual Basic .NET
- Visual Prolog
- Wart
- Whitespace
- Wortel
- XMIDAS
- XLISP
- XPL0
- XPath 2.0
- XSLT
- Yorick
- Z80 Assembly
- Zkl
- ZX Spectrum Basic