My code doesnt work and its going to infinte! I am stuck :(

Jul 27, 2018 at 6:11pm
Why is this code not working and going to infinite? X is read and I must find the X prime number. Example: X=4 --- the fourth prime number is 7 and so on. Thank you guys!

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
34
35
36
37
38
  #include <iostream>

using namespace std;

int main()
{
    int x, i, divz=0, count, nr, j, number=0;
    cin>>x;
    count=0;
    for(i=2;i<=x*x;i++)
        {
        for(j=1;j<=i;j++)
        {
        while(j<=i)
        {
            if(i%j==0) divz++;
            if(i!=j) continue;
            else
            {
                if(divz>2) 
                {
                    divz=0;
                    j++;
                }
                if(divz==2) 
                {
                    number++;
                    count++;
                    j++;
                    divz=0;
                }
            }
        }
        }
        }
    return 0;
}
Jul 27, 2018 at 6:39pm
Line 14: If the for from line 12 entered, then its condition (j<=i) is necessarily true, so the first time through this while will always enter.
Line 17: If the first time the while from line 14 entered j was less than i, then at this point i != j, since nothing else modified the value of either variable since line 14. The continue loops back to line 14, causing an infinite loop.

Remove the while from line 14. You don't need it.
Last edited on Jul 27, 2018 at 6:39pm
Jul 27, 2018 at 7:03pm
THANK YOUU! You saved meeee! Thanksss again
Topic archived. No new replies allowed.