This is very bothersome...

I have been working with this code on my own for a whole day and still confused on why it doesn't work.. So what I'm trying to do here is determine whether a number the user is prime or not. But instead of determining that it just puts "Number is prime" on every number entered. Is there a rounding problem of the double in the for loop? Please reply asap.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 #include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n = 0;
    bool is_prime = true;

    cout << "Enter a number." << endl;
    cin >> n;
    double square_root_of_n = sqrt(n);
    for(int i = 2; n <= square_root_of_n; i++)
    {
        if (n % i == 0)
        {
            is_prime = false;
            break;
        }
    }
    if (is_prime)
        {
        cout << endl << "Number is prime" << endl;
        }

    else 
        {
        cout << "Number is not prime.";
        }

return 0;
}
Last edited on
The exit condition in your for loop is wrong.

n <= square_root_of_n; will always be false and your for loop will exit immediately. Since is_prime is initially true, the next code block that checks if(is_prime) will always be true.

I think you meant to put:

1
2
3
4
    for(int i = 2; i <= square_root_of_n; i++)
    {
      ...
    }


The exit condition should be i <= square_root_of_n;
Last edited on
Now that was funny XD. Thanks for your help.
Topic archived. No new replies allowed.