Printing prime number from 1 to 100

前端 未结 7 1565
情书的邮戳
情书的邮戳 2021-02-11 10:12

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

7条回答
  •  无人共我
    2021-02-11 10:38

    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);
    

提交回复
热议问题