0
#include <iostream>
#include <cmath>

using namespace std;
bool prime(int n);

int main()
{
    double i;

    while (true)
    {
        cout << "Enter a number that isn't 0: ";
        cin >> i;
            if ( i == 0)
                break;
            if(prime(i))
                cout << i << " is prime" << endl;
            else
                cout << i << " is not prime." << endl;
    }
    system ("Pause");
    return 0;
}

bool prime (int n)
{
    int i;
    double sqrt_of_n = sqrt(double (n));
    for (i = 2; i <= sqrt_of_n; i++)
        {
            if (int(n) % 1 == 0)
            return false;
        }
    return true;
}

Everytime I run the program, if I input 7, I get that 7 isn't prime. Can someone help me figure out where I messed up?

I have tried changing between double and int for i and n.

If I input 3, it shows prime.

The problem is that it's showing some prime numbers as not prime.

1 Answers1

7

The body of your for loop doesn't use i at all.

In particular, n % 1 is always zero, for any integral n.

Presumably you want to know whether n is divisible by i, but accidentally checked if n is divisible by 1.

You could easily have discovered this mistake yourself by single-stepping in a debugger, and making the various subexpressions into "watch expressions".

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • I copied the example straight from a book called C++ without fear. This is how the book shows to do it. How do I remedy this error? – user3175649 Jan 11 '14 at 20:46
  • 1
    @user3175649 If this does come from a book, take another book... – Johan Jan 11 '14 at 20:47
  • 1
    @user3175649: I thought you might have copied someone else's code. At some point, an `i` was transcribed as `1`, because the two look very similar. I don't not know whether you made the error or it occurred during the prepublication process. Think about what I said, I'm not going to directly give you the answer, but there are plenty of clues here. – Ben Voigt Jan 11 '14 at 20:48
  • OH! If I replace the 1 in the for loop with i, it fixes it. My bad! Thanks :) – user3175649 Jan 11 '14 at 20:48
  • Thanks :) And I will definitely look into more books. This one is good, but it's not as good as some of the others I have seen. Thanks :) – user3175649 Jan 11 '14 at 20:48
  • 1
    @user3175649: take a look here: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Moha the almighty camel Jan 11 '14 at 20:49
  • @Mhd.Tahawi Thanks. I'll read through it :) – user3175649 Jan 11 '14 at 20:51