中級 0件解決済み 正答率0%

Amicable Pair

List every amicable pair whose two numbers are both at most a limit.

このチャレンジで学べること

  • Build a table of proper-divisor sums for every number up to a limit
  • Check a pair condition in both directions
  • Avoid listing a pair twice or listing perfect numbers

問題

翻訳を表示

Let s(n) be the sum of the proper divisors of n (its divisors other than n itself). Two different numbers a and b form an amicable pair when s(a) = b and s(b) = a. The smallest pair is 220 and 284: s(220) = 1 + 2 + 4 + 5 + 10 + 11 + 20 + 22 + 44 + 55 + 110 = 284 and s(284) = 1 + 2 + 4 + 71 + 142 = 220.

Implement amicable_pair(limit).

Computing s(n) for every n up to limit one at a time is slow. A sieve works better: for every d, add d to each multiple of d above d.

Input

limit: The largest number either member of a pair may have.

Output

Return a list of pairs [a, b] with a < b ≤ limit, sorted by a in ascending order. A pair is included only if both numbers are at most limit. Perfect numbers (where s(n) = n) are not pairs. If there are none, return an empty list.

制約

1 ≤ limit ≤ 200,000

例

例 1
入力:
limit = 1500

期待される出力:
expected = [
    [220, 284],
    [1184, 1210]
]
入力:
long long limit = 1500;

期待される出力:
std::vector<std::vector<long long>> expected = {
    {220, 284},
    {1184, 1210}
};
入力:
long limit = 1500;

期待される出力:
long[][] expected = new long[][] {
    new long[] {220, 284},
    new long[] {1184, 1210}
};

解説

s(220) = 284 and s(284) = 220, and s(1184) = 1210 and s(1210) = 1184. Both pairs fit under 1500: [[220, 284], [1184, 1210]].

例 2
入力:
limit = 250

期待される出力:
expected = []
入力:
long long limit = 250;

期待される出力:
std::vector<std::vector<long long>> expected = {};
入力:
long limit = 250;

期待される出力:
long[][] expected = new long[][] {};

解説

220 is at most 250, but its partner 284 is not, so no pair fits: [].

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

For every d from 1 to limit / 2, add d to the sums of 2d, 3d, 4d, and so on.

ヒント 2

For each a, let b be its divisor sum and check that b is in range and that b's divisor sum is a.

ヒント 3

Requiring a < b lists each pair once and skips perfect numbers.

目安の計算量

O(limit log limit) time, O(limit) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。