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