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 much more?
#include<iostream>
using namespace std;
int main() {
int i=2,j=2;
cout<<"Prime numbers between 1 and 100 are:"<<endl;
cout<<"2"<<"\t";
while(i!=100) {
for(int j=2;j<i;j++) {
if(i%j==0)
break;
if(j==i-1)
cout<<i<<"\t";
}
i++;
}
cout<<endl;
system("pause");
return 0;
}
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
iandj. So startiandjat 3, and increment them by 2.In addition to the trick mentioned above, I’ve added the condition
j*j<=iwhich logically is the exact same asj<=sqrt(i). There’s no need to compute the square root when you can do a simple multiplication.