Jump to content

  • Log In with Google      Sign In   
  • Create Account

Interested in a FREE copy of HTML5 game maker Construct 2?

We'll be giving away three Personal Edition licences in next Tuesday's GDNet Direct email newsletter!

Sign up from the right-hand sidebar on our homepage and read Tuesday's newsletter for details!


We're also offering banner ads on our site from just $5! 1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Calculating prime numbers with memoization


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
11 replies to this topic

#1 sooner123   Members   -  Reputation: 241

Like
1Likes
Like

Posted 18 December 2012 - 10:35 PM

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, 18 December 2012 - 11:07 PM.


Sponsor:

#2 0r0d   Members   -  Reputation: 819

Like
1Likes
Like

Posted 19 December 2012 - 02:31 AM

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]

#3 sooner123   Members   -  Reputation: 241

Like
0Likes
Like

Posted 19 December 2012 - 06:36 AM

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, 19 December 2012 - 06:37 AM.


#4 Celiasson   Members   -  Reputation: 504

Like
1Likes
Like

Posted 19 December 2012 - 07:19 AM

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, 19 December 2012 - 07:51 AM.


#5 Álvaro   Crossbones+   -  Reputation: 13645

Like
1Likes
Like

Posted 19 December 2012 - 09:03 AM

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[i]) {
	  ++n_primes;
	  for (unsigned long j = i*i; j < N; j+=i)
	    is_prime[j] = false;
    }
  }
  for (; i < N; ++i) {
    if (is_prime[i])
	  ++n_primes;
  }
  std::printf("%ld\n", n_primes);
}


#6 Álvaro   Crossbones+   -  Reputation: 13645

Like
1Likes
Like

Posted 19 December 2012 - 09:13 AM

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);
}


#7 iMalc   Crossbones+   -  Reputation: 2313

Like
1Likes
Like

Posted 19 December 2012 - 12:35 PM

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

#8 0r0d   Members   -  Reputation: 819

Like
1Likes
Like

Posted 19 December 2012 - 01:20 PM

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?

#9 Trienco   Crossbones+   -  Reputation: 2207

Like
1Likes
Like

Posted 19 December 2012 - 11:21 PM

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

#10 0r0d   Members   -  Reputation: 819

Like
1Likes
Like

Posted 19 December 2012 - 11:55 PM

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.

#11 sooner123   Members   -  Reputation: 241

Like
0Likes
Like

Posted 20 December 2012 - 01:01 AM

Wow lot of really helpful feedback.

0r0d, I'm compiling in MinGW, then running it there. "./a 10000000" etc.

#12 0r0d   Members   -  Reputation: 819

Like
0Likes
Like

Posted 20 December 2012 - 01:18 AM

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. =)




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS