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
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:
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.j += 2
instead of incrementing j
one by one Micro-optimizations:
++i
instead of i++
; the latter has a temporary variable in which it stores the original value of i
; the former does not.'\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.)