C ++ Increments for loop increment logarithmically

I want integers to be integers:

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

I have a code for this (see below), however it is cumbersome and is not generally programmed to different stop 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 a very difficult situation, which was mentioned above, so I would like to know a way to code this in a more general way, since for my requirements MAX will be on the order of 10 ^ 9, so using code like the above is too impractical.

+4
source share
1 answer

Try this code. This 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;
}
+6
source

Source: https://habr.com/ru/post/1613886/


All Articles