0

I was wondering what the issue was with my prime number code. I feel it might have to do with the arrangement of my repetition but I am not sure. The idea was as a prime number can only be divisible evenly by 1 and itself that I would use f_check to check this. It only out puts numbers 2 and 3. Where did I go wrong?

int [] f_numb;
double f_pri;
int f_check = 0;

f_numb = new int [101];

for (int cnto = 2; cnto<=100; cnto++) {

    f_numb [cnto] = cnto;

    for( int cnt=100; cnt>=1; cnt--) {
        f_pri = f_numb [cnto]%cnt;
        if (f_pri==0) {
             f_check=f_check+1;
        }
    }

    if (f_check == 2) {
        System.out.println(f_numb [cnto]);
        f_check = 0;

    }

}
Dave
  • 321
  • 1
  • 8
Justin Macrae
  • 53
  • 1
  • 8

1 Answers1

1

What happens when cnto is 4? You will increment f_check when cnt is 4, 2, and 1, totaling 3. Since f_check doesn't equal 2 it will miss your if statement and for the rest of your outer for loop it will never reset to zero and just keep incrementing f_check when a factor of a number is found.

NickLamp
  • 862
  • 5
  • 10
  • Thank you Nick! Now I see it, I missed a f_check = 0 statement after the if statement. So as you were saying f_check never gets reset at 4. Thank you so much it works now. Cheers dude. – Justin Macrae Feb 19 '16 at 02:17