Firstly, your code is short and correct, which is very good for a beginner .; -)
This is what I would do to improve the code:
1) Define variables within loops so that they are not confused with something else. I would also make a parameter or constant a border.
#define MAX 1000 for(int i=2;i<MAX;i++){ for(int j=2;j<i/j;j++){ if(!(i%j)) break; if(j>(i/j)) cout<<i<<" is prime\n"; } }
2) I would use the Sieve of Eratosthenes , as suggested by Joey Adams and Mau. Please note that I do not need to record this binding twice, so the two uses will always be identical.
#define MAX 1000 bool prime[MAX]; memset(prime, sizeof(prime), true); for(int i=4;i<MAX;i+=2) prime[i] = false; prime[1] = false; cout<<2<<" is prime\n"; for(int i=3;i*i<MAX;i+=2) if (prime[i]) { cout<<i<<" is prime\n"; for(int j=i*i;j<MAX;j+=i) prime[j] = false; }
Ratings are also worth considering. i*i<MAX is much faster than j > i/j , and you also do not need to mark any numbers <i * i because they have already been marked if they are compound. The most important thing is time complexity .
3) If you really want to quickly make this algorithm, you need to optimize its cache. The idea is to first find all the primes <sqrt (MAX) and then use them to find the rest of the primes. Then you can use the same memory block to search for all primes from 1024-2047, say, and then 2048-3071. This means that everything will be stored in the L1 cache. I once measured the acceleration of 12 times using this optimization on a sieve of Eratosthenes.
You can also reduce the use of space in half without storing even numbers, which means you don’t have to do the calculations to work on the new block often.
If you're a beginner, chances are you should just forget about the cache for now.
Jørgen fogh
source share