Returns the list of primes less or equal to the provided boundary. - Java java.lang

Java examples for java.lang:int prime

Description

Returns the list of primes less or equal to the provided boundary.

Demo Code


    //package com.java2s;
    import java.util.List;
    import java.util.stream.IntStream;
    import static java.util.stream.Collectors.toList;

    public class Main {
        /**//w w  w . jav  a 2  s.  c o  m
         * Returns the list of primes less or equal to the provided <code>boundary</code>.
         *
         * @param boundary - test boundary
         * @return list of primes
         */
        public static List<Integer> getPrimes(int boundary) {
    return IntStream.rangeClosed(2, boundary).filter(n -> isPrime(n)).boxed().collect(toList());
}

        /**
         * Tests if provided <code>number</code> is prime.
         *
         * @param number - a number to test
         * @return <code>true</code> if <code>number</code> is prime, <code>false</code> otherwise.
         */
        public static boolean isPrime(int number) {
    if (number <= 1) {
        return false;
    }

    double testBoundary = Math.sqrt(number);
    return IntStream.rangeClosed(2, (int) testBoundary).noneMatch(i -> number % i == 0);
}
    }

Related Tutorials