Amicale

 avatar
unknown
java
4 years ago
1.8 kB
7
Indexable
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class Ex04_NumereAmicaleBonus {
    private static int sumaDivizorilor(int num){
        int sum = 0;
        for (int i = 1; i <= num / 2; i++){
            if (num % i == 0){
                sum += i;
            }
        }
        return sum;
    }

    // This method computes all divisor sums from int to sup, returns a hashmap
    private static Map allDivisorSums(int inf, int sup){
        Map<Integer, Integer> allDivisorSum = new HashMap<>();
        for (int i = inf; i <= sup; i++){
            allDivisorSum.put(i, sumaDivizorilor(i));
        }
        return allDivisorSum;
    }

    // Returns a map with
    // key : a number / Value: the amical of this number
    private static Map<Integer, Integer> findAmicals(int inf, int sup){
        Map<Integer, Integer> inputHashMap = allDivisorSums(inf, sup);
        return inputHashMap.entrySet()
                .stream()
                .filter(elt -> elt.getKey().equals(inputHashMap.get(elt.getValue()))
                        && elt.getKey().compareTo(elt.getValue()) > 0)
                .collect(Collectors.toMap(elt -> elt.getKey(), elt -> elt.getValue()));
    }

    // This method prints the hashMap sorted by key
    public static void printAmicalsStream(int inf, int sup){
        Map<Integer, Integer> myMap = findAmicals(inf, sup);

        myMap.entrySet()
                .stream()
                .sorted(Map.Entry.<Integer, Integer>comparingByKey())
                .forEach(elt -> System.out.println(elt.getKey() + ", " + elt.getValue()));
    }
    public static void main(String[] args) {
        printAmicalsStream(1, 100_000);
    }
}
Editor is loading...