मध्यम 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

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 के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

हर कोडर का सबसे अच्छा पास हुआ समाधान। तेज़, कम मेमोरी वाले और बेहतर रेटिंग वाले समाधान ऊपर रहते हैं।

अभी कोई पास हुआ समाधान नहीं है। इसे हल करें और पहला स्थान पाएँ।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।