Arman - 1 year ago 51

Java Question

Lets say I have a for loop like this (ignore the terrible efficiency, this is just an example):

`ArrayList<Integer> primes = new ArrayList<>();`

for(int i = 0; i < 10000; i++){

if(isPrime(i)){

primes.add(i);

}

}

I want to display the progress of the loop at every interval of 10%, however I don't know how to do this without affecting the performance. This is all I can think of so far:

`ArrayList<Integer> primes = new ArrayList<>();`

int n = 10000/10;

for(int i = 0; i < 10000; i++){

if(isPrime(i)){

primes.add(i);

}

if(i == n){

System.out.println(String.valueOf(i).charAt(0)+"0% Complete");

n+=10000/10;

}

}

Is there a more efficient way of doing this?

Answer Source

I'm a fan of this approach:

```
ArrayList<Integer> primes = new ArrayList<>();
final int I_MAX = 10_000; final int N_MAX = I_MAX / 10;
for (int i = 0, n = 10; i < I_MAX; i++, n++, n %= N_MAX) {
if (i.isPrime()) primes.add(i);
if (n == 0) System.out.println((i / 10) + "0% complete");
}
```

You can also do something like this, which doesn't involve tracking another variable:

```
ArrayList<Integer> primes = new ArrayList<>();
final int I_MAX = 10_000;
for (int i = 0; i < I_MAX; i++) {
if (i.isPrime()) primes.add(i);
if (i % (I_MAX / 10) == 0) System.out.println(i / 10 + "0% complete");
}
```