Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Prime number test

  1. Aug 16, 2010 #1

    I'm new to programming and have written the following code to test for prime-ness, but it doesnt seem to work except for n = 3.

    I think it may have something to do with my goto statement. Can anyone see a way of avoiding this or any other errors with the program?

    Code (Text):

    #include <iostream>

    using namespace std;

    int main() {
        int n, i, is_prime;
        //Assume # is prime untill proven otherwise
        is_prime = true;
        // get number
        cout << "Enter a number and press ENTER (0 to exit): ";
        cin >> n;
        if (n == 0) {
            return 0;
        else {
            //test for prime-ness.
            while (i <= sqrt(static_cast<double>(n))) {
                if (n%i == 0)
                    cout << i << " is a factor of " << n << endl;
                    is_prime = false;
            if (is_prime)
                cout << "Number is Prime!" << endl;
                cout << "Number is not prime!" << endl;
        goto loop;
    Kind regards,

  2. jcsd
  3. Aug 16, 2010 #2


    User Avatar
    Science Advisor
    Homework Helper

    Always use { } with if statements - then hunt down the lecturer/textbook writer that misses them out for single line if statements.

    Then as a bonus appreciate the Python indentation rules
  4. Aug 16, 2010 #3
    What are the python indentation rules
  5. Aug 16, 2010 #4


    User Avatar
    Science Advisor
    Homework Helper

    When you do
    if ()
    .... this line
    .... another line

    Which line does the if() statement apply to in c/c++?
    In python, it's the indentation that controls the blocks, in c/c++ the indentation means nothing.
    Last edited: Aug 16, 2010
  6. Aug 16, 2010 #5
    Well, it's not a terribly efficient way to check for being prime, but it looks like it should work (except for any number less than 2, which it will think is a prime number). A quick scan makes me think that one of your problems is that you set is_prime to true OUTSIDE of your loop. So it'll work the first time you run it, and will continue to work until you give it a non-prime number, in which case it will continually return false, no matter what.

    But as mgb_phys points out, your bigger issue is that you should ALWAYS use { } around your code blocks, unless you've gained a knack for programming. As it stands, "is_prime = false" is performed EVERY time you're in your while loop, not just when n % i == 0. Hence, it works with 2 or 3, because it immediately falls out of the while loop (i = 2, and sqrt(3) and sqrt(2) are less than 2).

Share this great discussion with others via Reddit, Google+, Twitter, or Facebook