Can someone please tell me what is wrong with this code

black hole sun

New member
Hi guys, I am writing a simple program to print out 100 prime numbers in C++ (and no, I'm not doing 100 cout's ;) ). This is what I have so far, but for some unfathomable reason, it isn't working right. It compiles, but try to run it and you'll see what I mean.

Please, if you want to help, don't rewrite my program. just tell me what is wrong with my implementation, it is probably very simple but I just dont see the problem, and my code is well commented and indented. Thanks for any help.
Code:
//prints the first 100 prime numbers

// FIXME: for some reason this doesn't work. And I cant see why not...

#include <iostream>

using namespace std;

bool isPrime(const unsigned int);

int main(void)
{
    // start printing prime numbers from three
    int testNum = 3;

    cout << "I will now output, for your viewing pleasure, 100 prime numbers!" << endl;
    cout << "2, "; // manually print 2, the first prime number

     // i is only incremented if testNum really is prime
    for(int i = 1; i <= 100; )
    {
        bool j = isPrime(testNum);

        // if isPrime returns true...

        if(j == true)
        {
            cout << testNum << ", ";
            testNum++;
            i++;
        }
    }

    return 0;
}

bool isPrime(const unsigned int num)
{
    int dividedBy = num;

    // Assume the number is prime; therefore all I need to do
    // is test for non-prime characteristics, like if the number is even
    // or divisble by something.

    while(dividedBy > 2)
    {
        // first, check if the number is even
        if(num % 2 == 0)
            return false;

        // now, check if the number can be divided by anything,
        // because if the % returns 0,
        // then the number is NOT prime

        dividedBy--;

        int test = num % dividedBy;

        if(test == 0)
            return false;
    }

    // if we get this far without returning false, then
    // the number must be prime

    return true;
}


Just for reference, this below code is something I worked on with a fellow classmate of mine that determined whether or not an inputted number was prime. The above code is derived from this code, which works, and because it is a derived work I dont want to deviate too far from the original.

Code:
// asks for inputted number, then determines if the number is
// prime or or not prime.

#include <iostream>

using namespace std;

void getPrime(const unsigned int);
bool PRIME = true; //assume true

int main(void)
{
start: unsigned int number;
       cout << "Please input a number and I'll tell you if it's prime." << endl;
       cin >> number;

    getPrime(number);

    if (PRIME == true)
       cout << "Prime!" << endl;

    cout << "Look at another one?" << endl;
    char goAgain;
    cin >> goAgain;

    if(goAgain == 'y' || goAgain == 'Y')
    {
        // reset PRIME before we go again
        PRIME = true;
        goto start;
    }

    return 0;

}

void getPrime(const unsigned int num)
{
    // first, check if 0, 1, or 2 was entered
    if(num == 0 || num == 1)
    {
        cout << "Not prime.";
        return;
    }
    else if (num == 2)
    {
        cout << "Prime!" << endl;
        return;
    }


    int div = num;

    // Since PRIME is assumed true, all we do in this
    // while() is test and make sure the number is indeed prime
    while(div > 2)
    {
        if(num % 2 == 0)
        {
            cout << "Not prime." << endl;
            PRIME = false;
            return;
        }

        div--;

        int test = num % div;

        if(test == 0)
        {
            PRIME = false;
            cout << "Not prime." << endl;
            return;
        }
    }
}

I am a C++ newbie as you can tell, so go easy on me and don't do something wacky like put a pointer or array in there thanks ;)
 
Last edited:
Dude, I ain't a C++ developer, but Visual Basic.Net has similarities.
Your code will need to be put into a loop;

{
start: unsigned int number;
cout << "Please input a number and I'll tell you if it's prime." << endl;
cin >> number;

// Your loop will need to start here, incrementing the "number" variable by one
// each time instead of having a user input.
// your varification code should return true or false; use an arrayed variable
// to store your prime numbers for output.
// You will need to assign your arrayed variable as something like: Prime(99)
// As arrays are zero-based. (They start at 0, so the 100th value is Var(99)
// Use another variable which increments after your prime returns true: n+=1
// Before this number increments, use it as your array value: number=Prime(n)
// Finally, output the primes in a For x = 0 To 99 loop using x as your array
// value: cout(Prime(x) & Chr13) * Chr13 is Carriage return.
// Next x

getPrime(number);

if (PRIME == true)
cout << "Prime!" << endl;

cout << "Look at another one?" << endl;
char goAgain;
cin >> goAgain;

if(goAgain == 'y' || goAgain == 'Y')
{
// reset PRIME before we go again
PRIME = true;
goto start;
}

return 0;

}
 
The problem is that you are only incrementing testNum if it is prime.
Move the 'testNum++;' to after the 'if' block and you're golden.

BTW, you can increase the efficiency of 'isPrime' by starting dividedBy at num/2 since no number will be divisible by something larger than half of itself.

EDIT: But you'll have to move the dividedBy--; to below the mod check, othewise you won't check num/2.
 
Last edited:
Thanks noodles that did it. It is a pointless program...but one I'm proud of! :D

I'll also add your optimization. Thank you very much!
 
I think this could be a good benchmarking program if you tell it to, say, print a hundred THOUSAND prime numbers :D (I am attempting to do that by the way...my 2.0GHz Pentium M has been on it for ten minutes now and still going, I'm not sure when it's going to fail because of overflowing the int's I've used, but now it's up to six-digit prime numbers and it's really chugging along...)

Heres the complete, working code :D

Code:
//prints the first 100 prime numbers

// FIXME: for some reason this doesn't work. And I cant see why not...
// FIXED -- testNum was only getting incremented if testNum was prime..D'OH!

#include <iostream>

using namespace std;

bool isPrime(const unsigned int);

int main(void)
{
    // start printing prime numbers from three
    int testNum = 3;

    cout << "I will now output, for your viewing pleasure, 100 prime numbers!" << endl;

    // manually print 2, the (troublesome) first prime number
    cout << "2, ";

     // i is only incremented if testNum really is prime
    for(int i = 1; i < 100 ; ) // change 100 to however many prime numbers we want :)
    {
        bool j = isPrime(testNum);

        // if isPrime returns true...

        if(j == true)
        {
            cout << testNum << ", ";
            testNum++;
            i++;
        }

        // increment testNum if it is not prime
        else testNum++;
    }

    return 0;
}

bool isPrime(const unsigned int num)
{
    // optimize things a little bit by doing some dividedBy magic,
    // since no number will be divisible by something larger than
    // half of itself. with modern processors this means essentially
    // nothing, but a little opitmization is better than none, since this
    // is effectively a brute-force way to do things

    // NOTE: when computing, say, ten THOUSAND prime numbers, this
    // NOTICEABLY speeds up things! Go me! Well actually this optimization
    // is credited to 'noodles' of rage3d...thanks man! :)

    // the 1 is added to it to make the first 'dividedBy--;' work right

    int dividedBy = ((num / 2) + 1);


    // Assume the number is prime; therefore all I need to do
    // is test for non-prime characteristics, like if the number is even
    // or divisble by something.

    while(dividedBy > 2)
    {
        // first, check if the number is even
        if(num % 2 == 0)
            return false;

        // now, check if the number can be divided by anything,
        // because if the % returns 0,
        // then the number is NOT prime

        dividedBy--;

        int test = num % dividedBy;

        if(test == 0)
            return false;
    }

    // if we get this far without returning false, then
    // the number must be prime

    return true;
}
 
Last edited:
No problem.

I modified it to C, compiled it and ran it on my Linux box on a P4 2.6 and it took ~5 sec to find 100,000 numbers. :D

EDIT: I removed the print statements and it took less than 1 sec. Printing is VERY slow relatively speaking.
 
black hole sun said:
I think this could be a good benchmarking program if you tell it to, say, print a hundred THOUSAND prime numbers :D (I am attempting to do that by the way...my 2.0GHz Pentium M has been on it for ten minutes now and still going, I'm not sure when it's going to fail because of overflowing the int's I've used, but now it's up to six-digit prime numbers and it's really chugging along...)

Yeah...it really shouldn't take 10 min...
 
I was running it under Windows' cmd.exe. Figures, I guess :rolleyes:

Haven't had a chance to run it in linux.

EDIT: Okay, with slackware-current (using NPTL) it takes quite a long time...it was going on 4 minutes when I stopped it with no end in sight. There's no way it took just 5 seconds...removing the cout's didn't really help either.

In main() you have to change the for loop's test-expression to `i < 100000` to get a hundred thousand as right now it's at just a hundred. You probably just left off a zero, that's easy to do. Ten thousand primes are easy, they were printed in around 10 seconds, maybe that's what happened.

I can definitley see this as a benchmark because the numbers get REALLY large REALLY fast and that's a lot of loop work for the system.
 
Last edited:
Here you go:

I will now output, for your viewing pleasure, 100000 prime numbers!
...EDIT: REMOVED...

Run with:
time ./test

real 0m2.428s
user 0m0.059s
sys 0m0.057s

That is misleading though, it was acutally approx 5 secs.
when I run it like this: time ./test > log.txt

I get this:
real 0m0.157s
user 0m0.062s
sys 0m0.014s

This was actually < 1 sec.

Please don't tell me I don't know what I am doing.
 
Last edited:
I never said you didn't, I'm just absolutely amazed it finished in such a short amount of time, when for me it takes >5 minutes on linux and windows.

Something wrong on my end perhaps?

My processor is 600MHz slower, but it's a Pentium M...this has me a little worried now, heh.

Maybe it was because you changed it to C? How different is that code?
 
black hole sun said:
I never said you didn't, I'm just absolutely amazed it finished in such a short amount of time, when for me it takes >5 minutes on linux and windows.

Something wrong on my end perhaps?

My processor is 600MHz slower, but it's a Pentium M...this has me a little worried now, heh.

Maybe it was because you changed it to C? How different is that code?
I'm testing it on a p3 800, maybe it's intel? but I'd like to test the exact C code that we are trying to compare to, because < 1 second is just amazing.

Here's what I've got so far with the final cpp code submitted (but changed to 100 000):

Code:
 7733 nicholas  25   0  2272  772 2224 R 99.6  0.3   3:16.72 prime
and still going :(
 
noodles said:
Here you go:

I will now output, for your viewing pleasure, 100000 prime numbers!

100,000 odd numbers... :bleh:

done

Run with:
time ./test

real 0m2.428s
user 0m0.059s
sys 0m0.057s

That is misleading though, it was acutally approx 5 secs.
when I run it like this: time ./test > log.txt

I get this:
real 0m0.157s
user 0m0.062s
sys 0m0.014s

This was actually < 1 sec.

Please don't tell me I don't know what I am doing.

You don't know what you are doing...


jk...

Your algorithm is off... you just calculate odd numbers...


I was wrong before...i really might take 10 min...
 
Nuts, I am just doing odd numbers. Must look at code again.

Sorry.

Code:
/* Created by Anjuta version 1.2.3 */
/*	This file will not be overwritten */

#include <stdio.h>
#include <stdlib.h>

int isPrime(const unsigned int num);

int main(int argc, char **argv)
{
    int i = 0;
    int testNum = 3;
    int numtofind = 100000;

    printf ("I will now output, for your viewing pleasure, %d  prime numbers!\n", numtofind);

    // manually print 2, the (troublesome) first prime number
    printf ("2, ");

     // i is only incremented if testNum really is prime
    for(i = 1; i < numtofind ; ) // change 100 to however many prime numbers we want :)
    {
        int j = isPrime(testNum);

        // if isPrime returns true...

        if(j)
        {
            printf ("%d, ", testNum);
	    if (i % 10 == 0)
		printf ("\n");
            i++;
        }

        testNum++;
    }
	printf ("done\n");
    return 0;
}



int isPrime(const unsigned int num)
{
    // optimize things a little bit by doing some dividedBy magic,
    // since no number will be divisible by something larger than
    // half of itself. with modern processors this means essentially
    // nothing, but a little opitmization is better than none, since this
    // is effectively a brute-force way to do things

    // NOTE: when computing, say, ten THOUSAND prime numbers, this
    // NOTICEABLY speeds up things! Go me! Well actually this optimization
    // is credited to 'noodles' of rage3d...thanks man! :)

    // the 1 is added to it to make the first 'dividedBy--;' work right

    int dividedBy = ((num / 2) + 1);

    if (num % 2)
        return 1;

    // Assume the number is prime; therefore all I need to do
    // is test for non-prime characteristics, like if the number is even
    // or divisble by something.

    while(dividedBy > 2)
    {
        // now, check if the number can be divided by anything,
        // because if the % returns 0,
        // then the number is NOT prime

        dividedBy--;

        int test = num % dividedBy;

        if(test == 0)
            return 0;
    }


    // if we get this far without returning false, then
    // the number must be prime

    return 1;
}
 
Back
Top