This program is supposed to output the prime numbers between 1 and 100. Will anyone please explain me the flow the programme below? I am having difficulty in writing the progra
If you split the various parts out into their own methods with appropriate names it becomes a bit easier to understand:
for (int n = 1; n < 100; n++)
if (isPrime(n))
System.out.println(n);
private boolean isPrime(int n) {
for (int f = 2; f < n; f++) {
if (isFactor(f, n))
return false;
}
return true;
}
private boolean isFactor(int factor, int number) {
return number % factor == 0;
}
This is also an area where Java 8 streams can make things a bit clearer:
List primes = IntStream.range(1, 100)
.filter(this::hasNoFactors)
.collect(Collectors.toList());
private boolean hasNoFactors(int number) {
return IntStream.range(2, number)
.noneMatch(f -> number % f == 0);
}
Also note that this is a horribly inefficient algorithm. You don't need to check every possible factor from 2 to n, just the primes. You can also take advantage of multi-processor machines:
List primes = new ArrayList<>();
IntStream.range(2, 100)
.filter(n -> primes.parallelStream().noneMatch(p -> n % p == 0))
.forEach(primes::add);