r/ProgrammerHumor • • Jan 16 '14

[deleted by user]

[removed]

1.3k Upvotes

446 comments sorted by

View all comments

Show parent comment

1

u/tangerinelion Jan 17 '14

Inside the typical choices are:

string out = "";
if(i%3 == 0) { out += "Fizz"; }
if(i%5 == 0) { out += "Buzz"; }
if(out.length()) { 
    print out;
} else {
    print i;
}

or to consider the 4 possible choices explicitly:

if(i%15 == 0) { print "FizzBuzz"; }
else if(i%5 == 0) { print "Buzz"; }
else if(i%3 == 0) { print "Fizz;" }
else { print i; }

You do not want to add i%3 and i%5. You want the boolean AND, as i%3 == 0 && i%5 == 0 implies i%15 == 0. But i%3 + i%5 is only 0 for i == 15*n (n an int).