Diagram for the divisor-sum pair problem

The task is to find pairs of numbers below a given limit where each number's divisor sum equals the other number. Here the divisor sum deliberately excludes 1 and the number itself. That detail changes which pairs qualify, so the helper and the comparison must follow the same rule.

Building the divisor sum

For a number x, the helper starts from divisor 2 and tests up to sqrt(x). When i divides x, the matching divisor is x / i. If those two divisors are different, both are added; if they are the same, as in a perfect square, the shared divisor is added only once. Since the loop begins at 2 and only considers factor pairs with both members above 1, neither 1 nor x enters the sum.

Checking pairs

After reading n, the program loops i from 2 to n - 1 and, inside that, loops j from 2 to n - 1. It skips the case where i and j are equal, then checks both directions: yinzi(i) must equal j, and yinzi(j) must equal i. When both conditions hold, the pair is printed.

The nested loops cover the same range for i and j, so if a valid pair is found, the reversed order will also be reached later. The code below does not suppress that second output.

#include <iostream>
using namespace std;

// Define a function that returns the sum of a number's divisors (excluding 1 and itself)
int yinzi(int x ) {
    int i, c = 0;
    for(i = 2; i * i <= x; i++) {
        if(x % i == 0) {
            if(x / i != i) {
                c = c + i + x / i;
            } else {
                c = c + i;
            }
        }
    }
    return c;
}


int main() {
    int n;
    cin >> n;
    // Traverse M
    for (int i = 2; i < n; i++) {
        // Traverse N
        for (int  j = 2; j < n; j++) {
            // Condition check
            if(i != j) {
                if(yinzi(i) == j and yinzi(j) == i) {
                    cout << i << " " << j << endl;
                }
            }
        }
    }
}

The divisor helper is the part worth keeping clear: it reduces the search from every possible divisor to factor pairs up to the square root, while preserving the definition that leaves out 1 and the number itself. The pair check then follows directly from that definition.