I think you want to approach this differently. Factor the code into two functions, and merge them later if greater efficiency is required.
First write a function that prints a number, padded with leading zeros. Something like (padded-string x width). An easy implementation is to convert x to a string, compare the string's length to the desired width, and add leading "0"s as required.
Then write a function that makes a list of calls to padded-string. Print the biggest number in the range, find its width, and use that for padding all the other numbers.
- cache a long string of 0s, and index into it as required
- merge the two functions, so the main loop knows the string length before printing
... but don't do any of this until you have a working program! I have had too many cool programs die unfinished because I got distracted by some optimization like SSE2 or partial evaluation or ...
- Version control is your friend! Commit whenever you make progress. A good tool (e.g. git) lets you rewrite history to be beautiful as needed.
- It doesn't hurt to have parallel source files -- one set doing things the easy way, and the other with a bunch of optimizations.
- Always drive optimizations by benchmarks. Have a test suite showing what you may gain before ruining your code for nothing.
Ok. I went way off-topic there. Enjoy your day.