Search code examples
c++for-looplogarithm

c++ Increasing for loop increment logarithmically


I want to loop though integers like this:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, ..., 100, 200, ..., 1000, 2000, ...

I have code to do this (shown below) however it is cumbersome and not programmed generally to deal with different stopping limits:

int MAX = 10000;

for (int i = 1; i <= MAX; i++) {

    cout << i << endl;

    if (i >= 10 && i < 100) {
        i += 9;
    }

    else if (i >= 100 && i < 1000) {
        i+= 99;
    }

    else if (i >= 1000 && i < 10000) {
        i += 999;
    }

}

As you can see, this is very situation specified as mentioned previously - so I'd like to know of a way to code this in a more general way, as for my requirements MAX will be of the order of 10^9 so using code like above is far too impractical.


Solution

  • Try this code. It is more general:

    int MAX = 1000000;
    
    for (int i = 1, increment = 1, counter = 1; i <= MAX; i += increment) {
        cout << i << endl;
    
        if (counter == 10) {
            increment *= 10;
            counter = 1;
        }
        ++counter;
    }