Optimizing prime numbers code?

后端 未结 9 1775
别那么骄傲
别那么骄傲 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:20

    You are checking every number from 2 to 100. But since 2 is the only even prime number, you can skip every even number after 2. This goes for both i and j. So start i and j at 3, and increment them by 2.

    #include
    
    using namespace std;
    
    int main() {
        cout<<"Prime numbers between 1 and 100 are:"<i or when i is divisible by j.
            // The first condition means prime, the second, not prime.
            int j=3;
            for(;j*j<=i && i%j!=0; j+=2); // No loop body
    
            if (j*j>i) cout << i << "\t";
        }
        cout<

    In addition to the trick mentioned above, I've added the condition j*j<=i which logically is the exact same as j<=sqrt(i). There's no need to compute the square root when you can do a simple multiplication.

提交回复
热议问题