0

When the program is finding the prime numbers, it compiles.

But an error occurred during runtime. How can I fix it ?

What is the easiest way of finding prime numbers?

Error :

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at PrimeNumbers.main(PrimeNumbers.java:6)

Code :

import java.util.*;

class PrimeNumbers { 

    public static void main(String args[]) {
        for (int i = 0; i <= 100; i++) {
            for (int j = 0; j < i; j++) {
                if (i % j == 0) {
                    break;
                } else {
                    System.out.println(i);
                }
            }
        }
    }
}
Alexandre Beaudet
  • 2,774
  • 2
  • 20
  • 29

5 Answers5

1

You need to change your second for loop to start from 1 not 0. Because modular of zero is an error.

 for(int j=1;j<i;j++){
        if(i%j==0){
Oguz Ozcan
  • 1,497
  • 13
  • 21
1

You must change your code like this:

class PrimeNumbers{
public static void main(String args[])
{
    boolean flag;
    for(int i=1;i<=100;i++)
    {
        flag = true;
        for(int j=2;j<=(i/2);j++){
            if(i%j==0)
                flag = false;;
        if(flag == true)
           System.out.println(i);
    }
}
Hossein
  • 314
  • 3
  • 12
0

You have i = 0 and j = 0 in the first iteration of your loop. In order to obtain the modulus, i is divided by j. Therefore, you are performing in the first iteration:

0 / 0

Thus getting the divide by zero exception.

0

There are two possible ways of prime number calculation:

public static boolean isPrime(long num) {
    return num > 1 && LongStream.rangeClosed(2, (long)Math.sqrt(num)).noneMatch(div -> num % div == 0);
}

public static boolean isPrime1(long num) {
    for (long i = 2, sqrt = (long)Math.sqrt(num); i <= sqrt; i++)
        if (num % i == 0)
            return false;
    return true;
}

Main performance trick is enough to check first Math.sqrt(num) numbers only.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0
public static void main(String args[]){
            boolean flag=false;
            int i=1;
            while(i<=100){
                for(int j=2;j<=i/2;j++) {
                    if(i%j==0){
                        flag=true;
                        break;
                    }else {
                        flag=false;
                    }

                }
                 if(flag!=true) {
                        System.out.println("Prime number--->" +i);
                    }
                 i++;
            }

        }
Dora
  • 191
  • 8