Check Amicable Number in JavaScript

Beginner
⏱️ 13 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Number theory

What you’ll learn

  • The definition of an amicable pair using the sum of proper divisors s(n), and why a ≠ b matters.
  • A compact mathematical formulation and classic examples such as 220 and 284.
  • A clear algorithm, pseudocode, and two complete JavaScript examples (sqrt pairing and naive scan), plus Try it Yourself links.
  • Time and space complexity, common edge cases, and interview-style optimizations.

Overview

This page is an interview-style walkthrough: given two positive integers a and b, decide whether they form an amicable pair—each is the sum of the proper divisors of the other, and the two values are different.

Pair logic

Compute s(a) and s(b), then check s(a)=b, s(b)=a, and a≠b. Order of arguments does not matter.

Live preview

Try 220 and 284 (or your own values) in the browser before running the full scripts.

Tables and rigor

I/O examples, edge cases, and complexity notes cover the usual follow-ups.

Prerequisites

You should already be comfortable with basic JavaScript (functions, loops, and %) before following the examples below.

  • Comfortable running JavaScript in Node.js or the browser console, using function declarations and console.log.
  • for loops, integer arithmetic, and the modulo operator % to test divisibility.
  • The idea of proper divisors of n: positive divisors strictly less than n.

What is an amicable pair?

Write s(n) for the sum of all proper divisors of n (positive divisors of n that are strictly less than n). Two different positive integers a and b are an amicable pair when s(a) = b and s(b) = a.

That is a symmetric condition: swapping a and b does not change the answer. If a = b, you would only need s(a) = a, which defines a perfect number, not an amicable pair.

Amicable a ≠ b, s(a) = b, s(b) = a
Perfect s(n) = n
Not amicable fails any check above

Mathematical definition

Let s(n) denote the sum of proper divisors of n. Equivalently, if σ(n) is the sum of all positive divisors of n, then s(n) = σ(n) − n.

Formal condition

Positive integers a and b form an amicable pair if and only if a ≠ b, s(a) = b, and s(b) = a.

Smallest pair: 220 and 284. One checks s(220) = 284 and s(284) = 220.

Sketch for a = 220
  1. Proper divisors of 220 include 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110.
  2. Their sum is s(220) = 284.
  3. Proper divisors of 284 include 1, 2, 4, 71, 142, which sum to s(284) = 220.
  4. Since 220 ≠ 284, the two numbers are amicable.

Intuition and examples

Think of s(n) as “what smaller pieces sum to when you list every proper divisor of n.” An amicable pair is two different numbers that point at each other: the divisor-sum of the first lands on the second, and vice versa.

The cards contrast a true amicable pair with cases that fail one of the required equalities.

220 & 284 Amicable
s(220)
284
s(284)
220
Verdict
Both directions match and 220 ≠ 284amicable.
6 & 6 Not amicable
s(6)
1 + 2 + 3 = 6
Pair rule
Here a = b; the definition excludes identical values.
Verdict
6 is perfect, not part of an amicable pair with itself.
10 & 9 Not amicable
s(10)
1 + 2 + 5 = 8 (not 9)
s(9)
1 + 3 = 4 (not 10)
Verdict
Neither directed equality holds — not amicable.

Takeaway: always verify both s(a)=b and s(b)=a, and reject a=b unless the problem statement explicitly says otherwise.

Live preview

Enter two positive integers a and b. The tool computes s(a) and s(b) the same way as the naive loop (sum every proper divisor), then checks the amicable conditions. For large values with many divisors, long divisor lists are omitted but the sums stay exact. Everything runs in your browser.

  1. Try 220 and 284, or experiment with your own pair.
  2. Press Run check (or Enter in either field).
  3. Read whether the pair is amicable and which condition failed if not.

Use whole numbers a, b ≥ 1. Values above 999 999 are blocked so the tab stays responsive.

Live result
Press “Run check” to see s(a), s(b), and the amicable verdict.

Algorithm

Goal: given positive integers a and b, decide whether they form an amicable pair.

Validate inputs

Reject non-positive values if your program must follow the number-theory definition on counting numbers only.

Compute s(a) and s(b)

Sum every divisor d with 1 ≤ d < n and n % d == 0, or use a faster pairing method up to √n.

Enforce a ≠ b

If a == b, return false (or “not amicable”) even if s(a) == a, unless the assignment explicitly redefines the term.

Compare both directions

Return true if and only if s(a) == b and s(b) == a.

📜 Pseudocode

Pseudocode
function properDivisorSum(n):
    if n < 1:
        return invalid
    if n = 1:
        return 0
    sum ← 0
    for i from 1 to floor(n / 2):
        if n mod i = 0:
            sum ← sum + i
    return sum

function areAmicable(a, b):
    if a = b:
        return false
    return properDivisorSum(a) = b and properDivisorSum(b) = a
1

Check one pair (sqrt sum, with explanation)

sumOfDivisors returns s(n) in O(√n) time using divisor pairs. areAmicable rejects a === b and tests both directions.

JavaScript
/**
 * Sum of proper divisors s(n); s(1) = 0
 */
function sumOfDivisors(num) {
  if (num <= 1) {
    return 0;
  }
  let sum = 1;

  for (let i = 2; i * i <= num; i++) {
    if (num % i === 0) {
      sum += i;
      const pair = Math.floor(num / i);
      if (i !== pair) {
        sum += pair;
      }
    }
  }

  return sum;
}

function areAmicable(num1, num2) {
  if (num1 === num2) {
    return false;
  }
  return sumOfDivisors(num1) === num2 && sumOfDivisors(num2) === num1;
}

const a = 220;
const b = 284;

if (areAmicable(a, b)) {
  console.log(a + " and " + b + " are amicable numbers.");
} else {
  console.log(a + " and " + b + " are not amicable numbers.");
}
Try it Yourself

Explanation

The helper computes the same s(n) as a naive loop, but visits divisor pairs up to √n instead of scanning to n/2.

if (num <= 1) return 0;

Edge guard. There is no proper divisor of 1, so s(1)=0. This also avoids meaningless work for 0 or negatives if they slip in.

let sum = 1;

Include divisor 1 once. The loop starts at i = 2, so sum begins at 1.

if (num1 === num2) return false;

Disallow the trivial diagonal. A perfect number would satisfy s(a) === a; that is not an amicable pair in the usual definition.

return sumOfDivisors(num1) === num2 && sumOfDivisors(num2) === num1;

Both directions. You must check s(a)=b and s(b)=a; one equality alone is not enough.

2

Same pair check (naive divisor sum)

This version uses a loop to Math.floor(n / 2) for each sum. It is O(n) per value but matches the pseudocode line-for-line and is easy to explain first in an interview.

JavaScript
function sumOfDivisorsNaive(num) {
  if (num <= 1) {
    return 0;
  }
  let sum = 0;
  const half = Math.floor(num / 2);

  for (let i = 1; i <= half; i++) {
    if (num % i === 0) {
      sum += i;
    }
  }

  return sum;
}

function areAmicableNaive(num1, num2) {
  if (num1 === num2) {
    return false;
  }
  return (
    sumOfDivisorsNaive(num1) === num2 &&
    sumOfDivisorsNaive(num2) === num1
  );
}

const a = 220;
const b = 284;

if (areAmicableNaive(a, b)) {
  console.log(a + " and " + b + " are amicable numbers.");
} else {
  console.log(a + " and " + b + " are not amicable numbers.");
}
Try it Yourself

Explanation

The inner loop walks every candidate proper divisor; the outer logic is unchanged from Example 1.

for (let i = 1; i <= Math.floor(num / 2); i++)

Exhaustive proper divisors. Any proper divisor of num is at most num/2, so this range is sufficient.

areAmicableNaive

Same boolean test as the fast version; only the helper that computes s(n) differs.

Optimization

Single pair. Use divisor pairing up to √n for each s(a) and s(b) when inputs may be large.

Many pairs or a range. Precompute s(k) for all k in [1, N] with a sieve-like accumulation, then each pair test is O(1) lookups after O(N log N) setup.

Overflow. For very large n, use BigInt for sums or watch Number.MAX_SAFE_INTEGER when using normal JavaScript numbers.

Interview: write the naive sum first if time is short, then mention the sqrt speedup.

❓ FAQ

Two different positive integers a and b are amicable if the sum of proper divisors of a equals b, and the sum of proper divisors of b equals a. The smallest such pair is (220, 284).
No. The definition requires two distinct numbers. If a equals b, you would only need s(a)=a, which describes a perfect number, not an amicable pair.
There are no proper divisors of 1 in the usual convention, so s(1)=0. That keeps pair checks consistent and avoids wrong sums if the helper is called on 0 or 1.
All three notions use s(n), the sum of proper divisors. Perfect means s(n)=n. Abundant means s(n)>n. Amicable links two different numbers by s(a)=b and s(b)=a.
If each sum uses sqrt factorization, one pair check is O(sqrt(a)+sqrt(b)) arithmetic. A naive loop to n/2 per value is O(a+b).
Start with the clear loop to n/2 if you want speed to code. Mention the sqrt divisor-pair method when asked about large inputs or optimization.

🔄 Input / output examples

Assume literals a and b as in the sample scripts. For interactive input you could read from process.argv in Node.js or from form fields in a browser.

abTypical line printed
220284220 and 284 are amicable numbers.
284220284 and 220 are amicable numbers.
10910 and 9 are not amicable numbers.
666 and 6 are not amicable numbers.

Edge cases and pitfalls

These mistakes do not change the definition of amicable numbers; they change whether your program matches it.

Equality

a == b

Reject this case for a standard amicable-pair check. Otherwise a perfect number would be flagged incorrectly.

One-way

Only checking s(a) == b

You also need s(b) == a. Counterexamples are easy to construct if either check is dropped.

Sqrt loop

Perfect squares

When i * i == num, add i only once when pairing with num / i.

Bounds

s(1) and small values

Return 0 for n <= 1 so pair checks involving 1 do not mis-sum.

Overflow

Wide sums

For large n, s(n) can exceed safe integer precision; prefer BigInt when the problem demands huge values.

⏱️ Time and space complexity

TaskTimeExtra space
s(n) naive (1 .. n/2)O(n)O(1)
s(n) sqrt pairingO(√n)O(1)
areAmicable(a,b) (two sqrt sums)O(√a + √b)O(1)
areAmicable with two naive sumsO(a + b)O(1)

Beyond recursion depth, both sample scripts use only a handful of local variables: auxiliary space is constant.

Summary

  • Definition: distinct a, b with s(a)=b and s(b)=a. Classic example: 220 and 284.
  • Code: implement s(n) (naive or sqrt), then combine with a != b and two equalities.
  • Watch-outs: both directions, exclude a === b, square-root double-counting, and integer precision on very large inputs (BigInt / MAX_SAFE_INTEGER).
Did you know?

The pair 220 and 284 is the smallest amicable pair: each number equals the sum of the proper divisors of the other. Pythagoras is said to have known of them; they appear in early Greek and Arab manuscripts as symbols of friendship.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful