Name: Anonymous 2015-02-12 21:53
If you want an efficient FizzBuzz, you can unroll the loop to depth 15. Then, all your conditionals become constants, and you can optimize them all out. This means no modulo required, either.
It'd look something like:
local $, = "\n";
local $\ = "\n";
for ($i = 1; $i < 151; $i += 15) {
# 1 2 3 4 5 6 7
print $i, $i+1, "Fizz", $i+3, "Buzz", "Fizz", $i+6;
# 8 9 10 11 12 13 14 15
print $i+7, "Fizz", "Buzz", $i+10, "Fizz", $i+12, $i+13, "FizzBuzz";
}
Of course, if you need that sort of efficiency, you shouldn't be writing in Perl like I did above, and this method fails to adequately generalize to values much larger than 3 and 5. (It's unclear whether it'll beat the modulus-based solution even under perfect circumstances; it's much better in terms of branch prediction, but worse in terms of instruction cache locality, so you'd have to benchmark to see which factor was more important in practice.)
It'd look something like:
local $, = "\n";
local $\ = "\n";
for ($i = 1; $i < 151; $i += 15) {
# 1 2 3 4 5 6 7
print $i, $i+1, "Fizz", $i+3, "Buzz", "Fizz", $i+6;
# 8 9 10 11 12 13 14 15
print $i+7, "Fizz", "Buzz", $i+10, "Fizz", $i+12, $i+13, "FizzBuzz";
}
Of course, if you need that sort of efficiency, you shouldn't be writing in Perl like I did above, and this method fails to adequately generalize to values much larger than 3 and 5. (It's unclear whether it'll beat the modulus-based solution even under perfect circumstances; it's much better in terms of branch prediction, but worse in terms of instruction cache locality, so you'd have to benchmark to see which factor was more important in practice.)