Optimizing prime numbers code?

后端 未结 9 1774
别那么骄傲
别那么骄傲 2021-01-25 01:53

I wrote this code to show the primes between 1 and 100. The only condition is to do not use functions, whole code should be inline. I would ask if I can improve (optimize) it mu

9条回答
  •  悲&欢浪女
    2021-01-25 02:17

    Two simple optimizations you could do:

    cout << 2 << '\t';
    for (int i = 3; i <= 100; ++i) {
        for (int j = 3, l = (int)sqrt(i); j <= l; j += 2) {
            if (i % j == 0) {
                cout << i << '\t';
                break;
            } 
    } 
    

    What I did:

    Math:

    • Stop when j > sqrt(i), there's no need to go further than that. Note however that sqrt is an expensive function; for your small sample (from 1 to 100), it might (read, will surely) cost you more to use it.
    • Only check odd numbers; do j += 2 instead of incrementing j one by one

    Micro-optimizations:

    • Use ++i instead of i++; the latter has a temporary variable in which it stores the original value of i; the former does not.
    • Print '\t' as a character not as a string "\t".

    (These micro-optimizations are probably made automatically by the compiler anyway, but there's no harm in knowing about them.)

提交回复
热议问题