Loop Assignment 30 β€” Check Amicable Numbers Using a For Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check Whether Two Integers Are Amicable Numbers Using a For Loop

πŸ“‘ On this page:
  • What Makes Two Numbers Amicable?
  • The Divisor-Sum Algorithm
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
πŸ“š In this program, you will learn:
  • What "amicable numbers" means β€” and why 220 and 284 are the smallest example
  • How to compute the sum of proper divisors using a for loop, in O(√n)
  • Why looping up to √n and adding pairs of divisors is faster than looping to n
  • Why the check requires both s(a) == b and s(b) == a
  • How the same divisor-sum function powers perfect, deficient, and abundant number checks

What Makes Two Numbers Amicable?

Two numbers are amicable (or friendly) if the sum of the proper divisors of each equals the other. A "proper divisor" of n is any divisor of n other than n itself. So: let s(n) be the sum of the proper divisors of n. Then a and b are amicable if and only if s(a) == b and s(b) == a.

The classic example is 220 and 284. The divisors of 220 (other than 220) are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110 β€” and they sum to 284. The divisors of 284 (other than 284) are 1, 2, 4, 71, 142 β€” and they sum to 220. So 220 β†’ 284 β†’ 220, a closed loop of length 2. That's what makes them "amicable" β€” each number's divisor sum "answers" the other.

The concept goes back to Pythagorean times. The Pythagoreans considered 220 and 284 to be a symbol of friendship. The next amicable pair is 1184 and 1210, discovered much later (in 1866, by a 16-year-old named NicolΓ² Paganini, no relation to the violinist). Today, over a billion amicable pairs are known, and finding new ones is still a computational challenge.

A single number can be "perfect" if s(n) = n (like 6, 28, 496), "deficient" if s(n) < n, and "abundant" if s(n) > n. Amicable pairs are what you get when two different numbers each have the other as their divisor sum. The computational core is the same in all these cases: compute s(n) with a loop. That's the exercise.

πŸ’‘ In one line: compute the sum of proper divisors of each number with a for loop; the pair is amicable iff each sum equals the other number.

Diagram showing 220 and 284 with arrows pointing to each other; next to each number, the list of proper divisors and their sum, showing sum(220) = 284 and sum(284) = 220

The Divisor-Sum Algorithm

The whole program is two calls to a divisor-sum function plus a comparison:

s(n):
    sum = 1
    for i = 2 to sqrt(n):
        if n % i == 0:
            sum = sum + i
            if i != n / i:
                sum = sum + n / i
    return sum

amicable(a, b):
    return s(a) == b AND s(b) == a
                                

The subtle bit is the divisor-sum loop. It starts at 2 because 1 is always a divisor of every n (and always a proper divisor when n > 1). For each divisor i up to √n, it adds i, and then adds the paired divisor n / i β€” unless i equals n / i, which happens only when n is a perfect square. Adding both i and n / i in one iteration is what makes the loop O(√n) instead of O(n). If you loop all the way to n instead, the algorithm is still correct, just slower.

Pair (a, b) s(a) s(b) Amicable? Notes
(220, 284)284220βœ… YesSmallest pair, known since antiquity
(1184, 1210)12101184βœ… YesSecond smallest pair, found in 1866
(2620, 2924)29242620βœ… YesThird smallest pair
(6, 6)66❌ No6 is perfect, but amicable requires a β‰  b
(220, 285)284β€”βŒ Nos(220) = 284 β‰  285
(100, 200)117220❌ NoNeither sum matches
(1, 1)00❌ No1 has no proper divisors

Complete C Program

Program: check amicable numbers using a for loop

#include <stdio.h>

/* Return the sum of proper divisors of n. */
long long sum_proper_divisors(long long n) {
    if (n <= 1) return 0;
    long long sum = 1;                    /* 1 is always a proper divisor */
    for (long long i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            sum += i;
            if (i != n / i)
                sum += n / i;
        }
    }
    return sum;
}

int main(void) {
    long long a, b;

    printf("Enter two integers: ");
    if (scanf("%lld %lld", &a, &b) != 2 || a < 1 || b < 1) {
        printf("Invalid input. Enter two positive integers.\n");
        return 1;
    }

    long long sa = sum_proper_divisors(a);
    long long sb = sum_proper_divisors(b);

    if (sa == b && sb == a)
        printf("%lld and %lld are amicable numbers.\n", a, b);
    else
        printf("%lld and %lld are NOT amicable numbers.\n", a, b);

    return 0;
}
                                    

And here's a variant that finds all amicable pairs below a given limit, which is a nice way to explore the sequence and see the loop in action at scale:

Variant: find all amicable pairs up to N

#include <stdio.h>

long long sum_proper_divisors(long long n) {
    if (n <= 1) return 0;
    long long sum = 1;
    for (long long i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            sum += i;
            if (i != n / i) sum += n / i;
        }
    }
    return sum;
}

int main(void) {
    long long limit;
    printf("Find all amicable pairs up to: ");
    scanf("%lld", &limit);

    for (long long a = 2; a < limit; a++) {
        long long b = sum_proper_divisors(a);
        if (b > a && b < limit && sum_proper_divisors(b) == a)
            printf("(%lld, %lld)\n", a, b);
    }
    return 0;
}
                                    

The main program is the one to submit β€” it takes a single pair as input and answers yes or no. The variant is for exploration: run it up to 10,000 and you'll see (220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368) β€” all five amicable pairs below 10,000, in order. Notice the condition b > a: it ensures each pair is printed only once (as (a, b) with a < b), not twice.

Program Output

Enter two integers: 220 284
220 and 284 are amicable numbers.
                                

Try a few more. Input 1184 1210 and you should get "are amicable." Input 220 285 and you should get "are NOT amicable." Input 6 6 and you should get "are NOT amicable" β€” even though 6 is perfect, the pair (6, 6) is usually excluded from the definition (and in any case our check requires distinct numbers by convention). Input 1 1 and you should get "NOT amicable" since neither has proper divisors.

Enter two integers: 1184 1210
1184 and 1210 are amicable numbers.

Enter two integers: 100 200
100 and 200 are NOT amicable numbers.
                                

Step-by-Step Explanation

Let's walk through sum_proper_divisors(220) and see exactly how the loop works.

1. The base cases

if (n <= 1) return 0; handles 1 and any invalid input. 1 has no proper divisors β€” its only divisor is itself, and "proper" excludes it. So the sum is 0. Then sum = 1; initializes the accumulator with the divisor 1 that every number β‰₯ 2 has. This avoids starting the loop at 1 and duplicating the check.

2. The loop, iteration by iteration

For 220, √220 β‰ˆ 14.83, so the loop runs i from 2 to 14. Here's what happens:

  1. i = 2: 220 % 2 == 0, sum += 2 β†’ sum = 3, then i β‰  110 β†’ sum += 110 β†’ sum = 113.
  2. i = 3: 220 % 3 β‰  0 (2+2+0 = 4, not divisible by 3). Skip.
  3. i = 4: 220 % 4 == 0, sum += 4 β†’ sum = 117, then i β‰  55 β†’ sum += 55 β†’ sum = 172.
  4. i = 5: 220 % 5 == 0, sum += 5 β†’ sum = 177, then i β‰  44 β†’ sum += 44 β†’ sum = 221.
  5. i = 6: 220 % 6 β‰  0. Skip.
  6. i = 7: 220 % 7 β‰  0. Skip.
  7. i = 8: 220 % 8 β‰  0. Skip.
  8. i = 9: 220 % 9 β‰  0. Skip.
  9. i = 10: 220 % 10 == 0, sum += 10 β†’ sum = 231, then i β‰  22 β†’ sum += 22 β†’ sum = 253.
  10. i = 11: 220 % 11 == 0, sum += 11 β†’ sum = 264, then i = 20 β†’ sum += 20 β†’ sum = 284.
  11. i = 12, 13, 14: none divide 220.
  12. i = 15: 15Β² = 225 > 220 β†’ loop exits.

Final sum = 284. Correct.

3. The square-root subtlety

When n is a perfect square, the divisor √n appears twice in the paired-divisor enumeration β€” once as i and once as n / i. For example, for n = 36, the pair (6, 6) would be counted twice if we weren't careful. The check if (i != n / i) prevents this. Without it, 36 would report an inflated divisor sum. The pair (220, 284) doesn't trigger this case because neither is a perfect square, but the function must be correct for all inputs β€” that's the point of the check.

4. The full amicable check

Once we have sa = s(220) = 284 and sb = s(284) = 220, the test sa == b && sb == a becomes 284 == 284 && 220 == 220, which is true. Print "amicable." If only one direction matched β€” say s(a) = b but s(b) β‰  a β€” the pair wouldn't be amicable; the definition requires both directions. This "both directions" requirement is why the check is two comparisons with an &&, not just sa == b.

5. Why the loop is O(√n)

The loop runs from i = 2 to √n, which is about √n iterations. Each iteration does O(1) work. So the total is O(√n) β€” for n = 10⁢, that's about 1000 iterations, and for n = 10ΒΉΒ², about 10⁢ iterations (still very fast). If we looped from 1 to n instead, the algorithm would be O(n) β€” for n = 10ΒΉΒ², that's 10ΒΉΒ² iterations, which is completely impractical. The √n bound relies on the divisor-pairing observation: if d divides n and d < √n, then n/d > √n is the paired divisor, and every divisor greater than √n is paired with a divisor smaller than √n. So testing up to √n catches all divisors, in pairs.

6. Why long long instead of int?

Amicable numbers get large, and the divisor sum can exceed INT_MAX for moderately large inputs. For example, an abundant number near 2 Γ— 10⁹ can have a divisor sum in the billions. Using long long for the sum and for a and b avoids overflow for any reasonable input. The loop counter i must also be long long, because i * i can overflow int when i approaches 46,000 β€” which happens for n around 2 Γ— 10⁹.

7. Why 220 and 284 are the classic pair

The Pythagoreans discovered 220 and 284 and attributed mystical significance to them β€” 220 was associated with friendship and 284 with marriage. They're the smallest amicable pair, and no other pair was known in Europe until 1636, when Fermat discovered (17296, 18416). Euler found about 60 more in the 18th century. Today, over 10⁹ amicable pairs are known, all found by computer search. The 220/284 pair is the "hello world" of amicable numbers β€” simple enough to verify by hand, but deep enough to motivate the entire field.

🎯 Remember this: proper divisors exclude n itself; 1 is always a proper divisor (for n > 1); iterate to √n and add both i and n/i; skip the duplicate when i == n/i; and check both directions sa == b && sb == a. The whole check is O(√n).

Frequently Asked Questions

1. What is a "proper divisor"?

A proper divisor of n is any positive integer d that divides n, with d β‰  n. So the proper divisors of 12 are 1, 2, 3, 4, 6 β€” but not 12 itself. The sum of proper divisors is sometimes written Οƒ(n) βˆ’ n, where Οƒ(n) is the sum of all divisors (including n). By convention, 1 is the proper divisor of every n > 1, and the proper divisors of 1 are considered empty (sum 0).

2. Why check both s(a) == b and s(b) == a?

Because amicable numbers are defined as a symmetric relation: each number's divisor sum must equal the other. It's possible for s(a) = b but s(b) β‰  a β€” such pairs exist and are called "one-way" or "sociable-of-order-2-attempts", but they're not amicable. The formal definition requires both directions, so the check must use &&.

3. Why loop up to √n and not all the way to n?

Because divisors come in pairs. If d divides n and d < √n, then n/d > √n is also a divisor. So checking all d ≀ √n and adding both d and n/d catches every divisor. This reduces the loop from O(n) iterations to O(√n) β€” a massive speedup for large n. The only subtlety is avoiding double-counting when d = √n exactly (i.e., n is a perfect square), which is what the if (i != n / i) check handles.

4. Why does sum start at 1 instead of 0?

Because 1 is always a proper divisor of n (for n β‰₯ 2). Starting the sum at 1 is equivalent to including the divisor 1 without looping from i = 1 β€” saves one iteration and makes the loop range clean (i from 2 to √n). If you started at 0, you'd have to remember to add 1 separately or handle it inside the loop.

5. What's the difference between amicable, perfect, and sociable numbers?

A perfect number equals the sum of its proper divisors (e.g., 6, 28, 496). An amicable pair is two numbers that sum to each other (e.g., 220 and 284). A sociable chain is a cycle of length β‰₯ 3 β€” e.g., 12496 β†’ 14288 β†’ 15472 β†’ 14536 β†’ 14264 β†’ 12496 is a chain of length 5. All three are built on the same divisor-sum function; the only difference is the structure of the resulting graph.

6. How many amicable pairs are there?

At least 1.2 Γ— 10⁹ are known (as of 2024), and the count grows as computer searches extend. The smallest pair is (220, 284), the second smallest is (1184, 1210), and the third is (2620, 2924). Whether there are infinitely many is an open question β€” one of the many unresolved problems in number theory.

πŸ’‘ Tip: After this program, try the variant that finds all amicable pairs below 10,000 β€” it will output (220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368). Then modify the divisor-sum function to also return the count of proper divisors (not just the sum) and check the "amicable by count" variation. And if you're curious, try to prove that no amicable pair consists of two odd numbers that are both < 10⁢ β€” the smallest known odd amicable pair is (69615, 87633).

πŸ“– Related Tutorials

  • 28. Find the Largest Prime Factor Using a While Loop
  • 29. Iterative Binary Search Using a While Loop
  • 1. GCD of Two Numbers Using a While Loop (Euclidean Algorithm)
  • 3. Check Whether Two Numbers Are Coprime Using a While Loop
  • 4. Find All Common Divisors of Two Numbers Using a For Loop
  • C FOR Loop
  • While Loop
  • All 30 Loop Assignments

Previous Topic: -->> 29. Iterative Binary Search Using a While Loop   ||   Back to Index: -->> All 30 Loop Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.