// Prints the sum of factors of the integers 1 - 1,000,000.
// Second version with optimizations to compute the sum of
// n's factors more quickly by examining only up to sqrt(n).
import java.util.stream.*;

public class Perfect2 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        IntStream.range(1, 1000001)
            .filter(n -> n == sumDivisors(n))
            .forEach(System.out::println);
        double elapsed = (System.currentTimeMillis() - start)
                          / 1000.0;
        System.out.println();
        System.out.println("time = " + elapsed);
    }

    // returns the sum of the proper divisors of n
    public static int sumDivisors(int n) {
        int root = (int) Math.sqrt(n);
        int sum = IntStream.range(2, root + 1)
            .filter(x -> n % x == 0)
            .map(x -> x + n / x)
            .sum();
        if (n == root * root) {
            sum = sum - root;
        }
        return sum + 1;
    }
}
