<span> Sum by Factors </span>

public static String sumOfDivided(int[] s) {
        for (int i:s){
            primeFactors(i);
        }
        String[] res = {""};
        integers.forEach( x->{
            int sum = 0;
            boolean flag = false;
            for (int i:s){
                if (i%x == 0){
                    sum+=i;
                    flag=true; 
                }
            }
            if(flag)
                res[0]+="("+x+" "+sum + ")";
        });
        return res[0];

    }
    static  Set<Integer> integers = new TreeSet<>();
    private static void primeFactors( int n) {
        if (n<0) n =-n;
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) {
                integers.add(i);
                while (n % i == 0) {
                    n = n / i;
                }
            }
        }
        if (n > 1) {
            integers.add(n);
        }
    }
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务