Another Displaying Prime number exercise problem

This exercise ask me to make a program that uses boolean function to display all prime number from 1-100. When this is run it just gives all the value for i, is as if the function didn't do anything. I think it just that I don't know how a boolean function is suppose to be structured so it is not having any effect

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
//-------------------------------------------------
bool IsPrime(long number)
{
        int min = 2;
        for (number = min; number <= 100; number++)
        {    
            int x = 2;
            while (number%x!=0)
            x++;
            if (x==number)
            return true;
            
        }
}
//-----------------------------------------------------

int main(int argc, char *argv[])
{
        int i;
        for (i=2; i <= 100; i++)
        {
        if (IsPrime(i))
        cout << i << " is a prime number" << endl;
        }     
        
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
closed account (Lv0f92yv)
Remember that num mod num = 0; so when/if x is incremented enough (and it looks like it always will be, unless a smaller prime is found first), x will == number, which is also 0 using mod operator (thus returning true always).

Also, you should return some value ( presumably false here ) at the end, outside the for loop. If you ever get to this case, you determined it isn't a prime.
how do I return false value outside the loop?


1
2
3
4
5
6
7
8
9
10
for (number = min; number <= 100; number++)
        {    
            int x = 2;
            while (number%x!=0)
            x++;
            if (x==number)
            return true;
            
        }
return false
closed account (Lv0f92yv)
You're doing it in that example. After the loop exits, if you haven't hit the return statement inside it, then you know your check (if x == number ) must be false.

return false is all you need, and you will inevitably hit that statement and return false if the condition in the loop never truevaluates.
The logic looks a little bit wrong. Whatever value this function is copying from main(); will become 2 inside in your for loop.

number=min ,

it means you are checking every time the same condition. Where number is 2. So either it will yield always true or always false depend on other arguments.

May be I am wrong. But it looks like this to me.
Topic archived. No new replies allowed.