• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
sooner123

Calculating prime numbers with memoization

11 posts in this topic

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
1

Share this post


Link to post
Share on other sites
I looked at the code a little bit, didnt have a lot of time. Didnt see an easy way to rewrite and take out [i]isPrime[/i], 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]
1

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
0

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
1

Share this post


Link to post
Share on other sites
If you just want to count primes, this code is much faster:
[code]#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);
}
[/code]
1

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':
[code]#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);
}
[/code]
1

Share this post


Link to post
Share on other sites
[quote name='sooner123' timestamp='1355920567' post='5012412']
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.
[/quote]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.
1

Share this post


Link to post
Share on other sites
[quote name='sooner123' timestamp='1355920567' post='5012412']
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.
[/quote]

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?
1

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

Share this post


Link to post
Share on other sites
[quote name='Trienco' timestamp='1355980874' post='5012713']
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).
[/quote]

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

Share this post


Link to post
Share on other sites
Wow lot of really helpful feedback.

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

Share this post


Link to post
Share on other sites
[quote name='sooner123' timestamp='1355986896' post='5012723']
0r0d, I'm compiling in MinGW, then running it there. "./a 10000000" etc.
[/quote]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. =)
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0