print a series of numbers optimization part 1

≯℡__Kan透↙ 提交于 2019-12-25 01:07:03

问题


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);
    number = 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?


回答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.




回答2:


Will this do?

while(true)
{
    print("123456789");
}



回答3:


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:

  1. Convert the while loop to a for loop
  2. Convert increment + conditional to increment + mod operation.

This really is a case of micro-optimization.




回答4:


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.




回答5:


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;
}


来源:https://stackoverflow.com/questions/5767916/print-a-series-of-numbers-optimization-part-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!