• Advertisement
Sign in to follow this  

Calculating prime numbers with memoization

This topic is 1858 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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] Edited by sooner123

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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. Edited by sooner123

Share this post


Link to post
Share on other sites
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 ^^ Edited by PwFClockWise

Share this post


Link to post
Share on other sites
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);
}

Share this post


Link to post
Share on other sites
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);
}

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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?

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

0r0d, I'm compiling in MinGW, then running it there. "./a 10000000" etc.
I'm not really familiar with MinGW. What level of optimizations do you specify when compiling?

It's not really important... it's just that I noticed when I made my change, in the debug build it made a big difference in performance, but much smaller gains in release. I'm building using Visual Studio, with the default debug/release configuration. Since you said it ran "a lot faster", I was just wondering if you were testing using debug compile settings... which is never a good idea, but is easy to forget when you're doing quick performance testing. =)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement