Amicable Pair

题目:

An amicable pair (m,n) consists of two integers m,n for which the sum of proper divisors (the divisors excluding the number itself) of one number equals the other.

Given an integer k, find all amicable pairs between 1 and k.

Example:Given 300, return [[220, 284]].

分析:

这道题目教会了我一个深刻的道理,public static,如果不写static,真不能AC...具体为什么,上课时候要去问一下

解法:

public class Solution {
    /**
     * @param k an integer
     * @return all amicable pairs
     */
    public static int factorSum(int num) {
        int res = 1;
        for (int i = 2; i * i < num; i++) {
            if (num % i == 0) {
                res += i + num / i;
            }
        }
        return res;
    }

    public static List<List<Integer>> amicablePair(int k) {
        // Write your code here
        List<List<Integer> > res = new ArrayList<List<Integer> >();
        for (int i = 2; i < k; i++) {
            int temp = factorSum(i);
            if (temp < i || temp > k) {
                continue;
            }
            if (i == factorSum(temp) && i != temp) {
                ArrayList<Integer> pair = new ArrayList<Integer>();
                pair.add(i);
                pair.add(temp);
                Collections.sort(pair);
                res.add(pair);
            }
        }
        return res;
    }
}

results matching ""

    No results matching ""