print a series of numbers optimization part 1
lets say you want to make a program that will print the numbers 1-9 over and over again
123456789123456789123456789
i guess the most obvious way to do it would be to use a loop
int number = 1;
while(true)
{
print(number);
numb开发者_Go百科er = number + 1;
if(number > 9)
number = 1;
}
before i go any further, is this the best way to do this or is there a more common way of doing this?
Will this do?
while(true)
{
print("123456789");
}
Everyone using the %
operator so far seems to be under the impression that ten values are involved. They also overlook the fact that their logic will sometimes generate 0
. One way to do what you want is:
int i = 1;
while (true) {
print(i);
i = (i % 9) + 1;
}
The most obvious way would be this:
for (;;)
{
for (int i = 1; i < 10; ++i)
{
print(i);
}
}
Why you'd want to optifuscate it is beyond me. Output is going to so overwhelm the computation that any kind of optimization is irrelevant.
First off, why are you trying to "optimize" this? Are you optimizing for speed? Space? Readability or maintainability?
A "shorter" way to do this would be like so:
for (int i = 1; true; i++)
{
print(i);
i = (i + 1) % 10;
}
All I did was:
- Convert the while loop to a for loop
- Convert increment + conditional to increment + mod operation.
This really is a case of micro-optimization.
My answer is based off Mike's answer but with further optimization:
for (int i = 1; true; i++)
{
std::cout << ('0' + i);
i = (i + 1) % 10;
}
Printing a number is way more expansive then printing a char and addition.
精彩评论