javadividebyzeroexception

Can't see where I'm dividing by 0?


Here is all the code I think anyone would need to be able to asses my problem

1 import.java.util.Scanner
2 public class ccattano_Sieve{
3         private boolean []  primes = new boolean [50001];
4         private int upper;
5         private int lower;
6 
7         public ccattano_Sieve(){
8             upper = 50000;
9             lower = 1;
10            for (int i = 2; i < primes.length; i++){
11                primes[i] = true;
12            }
13            primes[0] = false;
14            primes[1] = false;
15        }
16 
17        public void processSieve(){
18            for (int i = 2; i < Math.round(Math.sqrt(50000)); i++){
19                if (primes[i] == true){
20                    for (int c = 2; c < (primes.length - 1); i++){
21                        if (c % i == 0){
22                            primes[c] = false;
23                        }
24                        else{
25                            primes[c] = true;
26                        }
27                    }
28                }
29            }
30        }

I'm pretty sure my else statement on lines 24 - 26 aren't needed I added it when trying to trouble shoot. But on line 21 when trying to run the code I receive a divide by zero error. The exact error is as follows.

Exception in thread "main" java.lang.ArithmeticException: / by zero
at ccattano_Sieve.processSieve(ccattano_Sieve.java:21)
at ccattano_SieveTest.main(ccattano_SieveTest.java:7)

This line "at ccattano_SieveTest.main(ccattano_SieveTest.java:7)" calls the code I pasted so it can be ignored. So line 21 is the main issue and I can't find a solution.


Solution

  • The modulus operator is the "rest of the division" meaning that it involves a division.

    I believe you have a bug on line 20 where you are incrementing i instead of c. This means the i variable will overflow (reach so high that it will turn negative) and eventually will turn into 0.