Amicable Pair (相亲数)

package _interview_question

/**
 * Given a integer n, return all amicable paris
 * */
class Solution16 {
    /*
    * solution: get sum of divisors of number,Time:O(nlogn), Space:O(1)
    * 一对整数是相亲数是说他们各自的所有有效因子(除了自己以外的因子)之和等于另外一个数。比如 (220, 284) 就是一对相亲数。因为:
    1. 220的所有因子:1+2+4+5+10+11+20+22+44+55+110 = 284
    2. 284的所有因子:1+2+4+71+142 = 220
    * */
    fun amicablePairs(n: Int): List<List<Int>> {
        val result = ArrayList<ArrayList<Int>>()
        for (i in 1..n) {
            val sum = getFactorsSum(i)
            if (sum <= i || sum > n) {
                continue
            }
            if (getFactorsSum(sum) == i) {
                val pairs = ArrayList<Int>(2)
                pairs.add(i)
                pairs.add(sum)
                result.add(pairs)
            }
        }
        return result
    }

    /**
     * calculate the sum of proper divisors
     * */
    private fun getFactorsSum(n: Int): Int {
        var sum = 1
        //Time:O(n)
        /*for (i in 1..n) {
            if (n % i == 0 && i != n) {
                sum += i
            }
        }*/
        //Time:O(logn)
        var i = 2
        while (i * i < n) {
            if (n % i == 0) {
                sum += i + n / i
            }
            i++
        }
        return sum
    }

    /**
     * return the number of pairs in the array that form an amicable pair.
     * */
    private fun amicablePairsCount(array: IntArray): Int {
        var count = 0
        for (i in array.indices) {
            for (j in i + 1 until array.size) {
                if (isAmicablePairs(array[i], array[j])) {
                    count++
                }
            }
        }
        return count
    }

    private fun isAmicablePairs(a: Int, b: Int): Boolean {
        return getFactorsSum(a) == b && getFactorsSum(b) == a
    }
}

 

posted @ 2020-12-19 17:05  johnny_zhao  阅读(201)  评论(0编辑  收藏  举报