Calculating prime numbers with memoization

Started by
10 comments, last by 0r0d 11 years, 4 months ago
My code is working, but is there a way I could get rid of the need for the 'isPrime' variable. It seems redundant.

I'd like to do this without a major restructuring of the code if possible.


[source lang="cpp"]#include <time.h>
#include <math.h>
#include <iostream>
#include <cstdlib>

int main(int argc, char*argv[]){
clock_t startTime = clock();

int maxToTest = atoi(argv[1]);
int*primes = new int[maxToTest];

primes[0] = 2;
int maxPrimeIndex = 0;

for (int i=3; i<=maxToTest; i++){
int isPrime = 1;
for (int j=0; (isPrime)&&(primes[j] <=sqrt(i)); j++) if (!(i%primes[j])) isPrime = 0;
if (isPrime) primes[++maxPrimeIndex]=i;
}

std::cout << maxPrimeIndex + 1 << " primes <= " << maxToTest
<< " found in " << (clock() - startTime)/CLOCKS_PER_SEC << " seconds";
}[/source]
Advertisement
I looked at the code a little bit, didnt have a lot of time. Didnt see an easy way to rewrite and take out isPrime, but I did make some changes that should speed things up a little. (also some other changes for readability... and fixed your time print code) =)

[source lang="cpp"]int main(int argc, char*argv[])
{
clock_t startTime = clock();

int maxPrimeIndex = 0;
int maxToTest = atoi(argv[1]);

int *primes = new int[maxToTest];
primes[0] = 2;

for (int i=3; i<=maxToTest; i+=2)
{
bool isPrime = true;
for (int j=0; isPrime && (primes[j] * primes[j] <= i); j++)
{
if (i % primes[j] == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
primes[++maxPrimeIndex] = i;
}
}

std::cout << maxPrimeIndex + 1 << " primes <= " << maxToTest
<< " found in " << (float)(clock() - startTime)/CLOCKS_PER_SEC << " seconds";
}[/source]
Wow that runs a lot faster. Thanks

Mainly it's removing the sqrt function.

Are you sure that break; accomplishes anything? I think the "isPrime &&" part of the for loop's conditional accomplishes the same thing.
I'm not entirely sure what's going on in the loops, but break will simply terminate that for-loop and jump back to the first one. So this is a performance gain since isPrime is set to false the first time you get into that if-statement. You don't need to continue that for-loop. So you will gain all those checks against the if-statement that are left to do once isPrime is false.

I might be wrong though ^^
If you just want to count primes, this code is much faster:
#include <cstdio>
#include <vector>

int main(int argc, char **argv) {
long N;
std::sscanf(argv[1], "%ld", &N);
long n_primes = 0;

std::vector<bool> is_prime(N, true);
is_prime[0] = is_prime[1] = false;
long i;
for (i = 2; i*i < N; ++i) {
if (is_prime) {
++n_primes;
for (unsigned long j = i*i; j < N; j+=i)
is_prime[j] = false;
}
}
for (; i < N; ++i) {
if (is_prime)
++n_primes;
}
std::printf("%ld\n", n_primes);
}
This is how I would implement code closer to what you originally posted, without a variable like `isPrime':
#include <cstdio>

bool is_prime(long n) {
if (n%2==0)
return n==2;
if (n%3==0)
return n==3;
for (long k=5; k*k<=n; k+=6) {
if (n%k==0 || n%(k+2)==0)
return false;
}
return true;
}

int main(int argc, char **argv) {
long N;
std::sscanf(argv[1], "%ld", &N);
long n_primes = 0;

for (long i=2; i<N; ++i) {
if (is_prime(i))
++n_primes;
}
std::printf("%ld\n", n_primes);
}

Wow that runs a lot faster. Thanks

Mainly it's removing the sqrt function.

Are you sure that break; accomplishes anything? I think the "isPrime &&" part of the for loop's conditional accomplishes the same thing.
Yes they both accomplish the same thing, so having both is redundant. However the break is the better one to use because the anded condition takes time on every iteration of the loop whereas the break only has any effect when the if-statement is true.
In general having multiple conditions in the for-loop continuation condition is best avoided.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

Wow that runs a lot faster. Thanks

Mainly it's removing the sqrt function.

Are you sure that break; accomplishes anything? I think the "isPrime &&" part of the for loop's conditional accomplishes the same thing.


Ahh, yeah, I didnt notice that. The break is the way to go since it terminates the for loop right away, so you dont need the bool check at all:
[source lang="cpp"]int main(int argc, char*argv[])
{
clock_t startTime = clock();

int maxPrimeIndex = 0;
int maxToTest = atoi(argv[1]);

int *primes = new int[maxToTest];
primes[0] = 2;

for (int i=3; i<=maxToTest; i += 2)
{
bool isPrime = true;
for (int j=0; primes[j] * primes[j] <= i; j++)
{
if (i % primes[j] == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
primes[++maxPrimeIndex] = i;
}
}

std::cout << maxPrimeIndex + 1 << " primes <= " << maxToTest
<< " found in " << (float)(clock() - startTime)/CLOCKS_PER_SEC << " seconds";
}
[/source]
It's a little cleaner this way and might even be a little faster. Yeah, the main win is the removal of the sqrt function, but also skipping the even numbers, which are guaranteed to not be prime.

Out of curiosity, are you testing in debug or release?
Of course replacing the static value of sqrt(i) with a multiplication that needs to be done on every iteration will eventually be slower, if your i gets really big (as in "unlikely big").

The biggest performance issue in the original code would seem to be doing the sqrt in the loop condition and pointlessly calculate it every single time (unless the compiler is friendly enough to optimize that out).
f@dzhttp://festini.device-zero.de

Of course replacing the static value of sqrt(i) with a multiplication that needs to be done on every iteration will eventually be slower, if your i gets really big (as in "unlikely big").

The biggest performance issue in the original code would seem to be doing the sqrt in the loop condition and pointlessly calculate it every single time (unless the compiler is friendly enough to optimize that out).


Good point, I didnt even notice that the sqrt() could just be pulled out of the inner for loop.

This topic is closed to new replies.

Advertisement