How can I get fireworks?

From the Super Mario Wiki:

At the end of every level in Super Mario Bros., with the exception of a castle level, fireworks would go off when Mario or Luigi entered the tiny castle (if the last number of the timer is 1, 3, or 6 at the end of the level). If the last number was 1, one firework would go off; if the last number was 3, three fireworks would go off and so forth. Each explosion would award the player with 500 points.

The page also details the appearance of fireworks in numerous other Mario titles.