Coprime numbers and Euler's totient in JavaScript
Intermediate · 4 min read
Two numbers are coprime when the only whole number that divides both of them is 1. 8 and 15 are coprime. 8 and 12 are not, because 4 divides both. Coprime pairs turn up in fractions that can't be simplified, in gear ratios that spread wear evenly, and in the math behind RSA encryption.
In this tutorial you will write coprime(a, b), then use it to count how many numbers from 1 to n are coprime with n. That count has a name, Euler's totient, and a neat shortcut formula. You will build both and check that they agree. You need to know loops, arrow functions and the GCD from the previous exercises.
Coprime means "GCD is 1"
The GCD (greatest common divisor) of two numbers is the biggest number that divides both. If the GCD is 1, they share nothing, so they are coprime. That is the whole test.
A common mix-up is to think coprime numbers must be prime. They don't. 8 is 2 times 2 times 2, and 15 is 3 times 5. Neither is prime, but they have no factor in common, so they are coprime. Coprime is a fact about the pair, not about either number.
What the totient counts
The totient of n, written φ(n) and said "phi of n", is how many numbers from 1 to n are coprime with n. For 10, those numbers are 1, 3, 7 and 9, so φ(10) is 4. Every even number shares 2 with 10, and 5 shares 5.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
41 Coprime numbers, and counting them
fairDecide whether two numbers share any factor beyond 1. Then count how many numbers from 1 to n are coprime with n, and check that count against the product formula.
Stuck? Three hints, smallest first
- 1. Coprime means the GCD is exactly 1. Neither number has to be prime.
- 2. Consecutive integers are always coprime, so
gcd(n, n + 1)is 1 for everyn. - 3. The count has a product form: take
nand multiply by(p - 1) / pfor each distinct primepdividing it.
Step 1: a GCD to build on
const gcd = (a, b) => {
a = Math.abs(a);
b = Math.abs(b);
while (b) [a, b] = [b, a % b];
return a;
};
console.log(gcd(8, 12)); // 4
console.log(gcd(8, 15)); // 1
This is Euclid's method: replace the pair with the smaller number and the remainder, until the remainder is 0. What is left in a is the GCD.
Step 2: the coprime test
const coprime = (a, b) => gcd(a, b) === 1;
console.log(coprime(8, 15)); // true
console.log(coprime(8, 12)); // false
console.log(coprime(1, 1)); // true
One line. Notice that 1 is coprime with everything, even itself, because the GCD of 1 and anything is 1.
Two neighbors, like 20 and 21, are always coprime. Any number dividing both would also divide their difference, which is 1. Numbers two apart are coprime only when the smaller one is odd:
console.log(coprime(5, 7)); // true
console.log(coprime(6, 8)); // false: both are even
Step 3: count the coprimes directly
The obvious way to find φ(n) is to try every number from 1 to n and count.
const totientByCounting = (n) => {
let count = 0;
for (let k = 1; k <= n; k++) if (coprime(k, n)) count++;
return count;
};
console.log(totientByCounting(10)); // 4
console.log(totientByCounting(13)); // 12
For a prime like 13, every number below it is coprime with it, so φ(13) is 12. This version is easy to trust, but it runs a GCD for every number up to n. For a number in the billions that is far too slow.
Step 4: find the distinct primes of n
The shortcut needs the different primes that divide n. For 12, which is 2 times 2 times 3, those are 2 and 3. We try divisors from 2 upward, and when one divides n, we record it and then divide it out completely so it can't be counted twice.
const distinctPrimes = (n) => {
const out = [];
for (let d = 2; d * d <= n; d++) {
if (n % d !== 0) continue;
out.push(d);
while (n % d === 0) n /= d;
}
if (n > 1) out.push(n);
return out;
};
console.log(distinctPrimes(12)); // [ 2, 3 ]
console.log(distinctPrimes(1000)); // [ 2, 5 ]
console.log(distinctPrimes(97)); // [ 97 ]
The loop only needs to go while d * d <= n. Whatever is left above 1 at the end is itself a prime, so it gets pushed too.
Step 5: the product formula
For each distinct prime p of n, a fraction 1/p of the numbers up to n share that prime. So you start with n and, for each p, keep (p - 1)/p of what is left. The obvious way to write that is a multiply by a fraction:
console.log(36 * (1 - 1 / 2) * (1 - 1 / 3)); // 12.000000000000002
36 has primes 2 and 3, and φ(36) is 12. But 1 / 3 can't be stored exactly, so a tiny error creeps in. The fix is to divide by p first, which is always exact because p divides what is left, and then multiply by p - 1:
const totient = (n) => distinctPrimes(n).reduce((acc, p) => (acc / p) * (p - 1), n);
console.log(totient(36)); // 12
console.log(totient(10)); // 4
console.log(totient(1000)); // 400
reduce starts with n and applies each prime in turn. Dividing first also keeps the numbers small along the way.
Step 6: check the two against each other
const ns = [1, 9, 10, 12, 36, 1000];
console.log(ns.map(totient)); // [ 1, 6, 4, 4, 12, 400 ]
console.log(ns.map(totientByCounting)); // [ 1, 6, 4, 4, 12, 400 ]
They match, including at 1, where there are no primes, so reduce just returns its starting value of 1.
The full solution
The answer panel builds gcd, coprime, both totient versions and distinctPrimes, then prints the 8 and 15 pair, the totients of 10 and 1000, and the coprime pattern for numbers one and two apart. Press Run to see the output.
const gcd = (a, b) => {
a = Math.abs(a);
b = Math.abs(b);
while (b) [a, b] = [b, a % b];
return a;
};
const coprime = (a, b) => gcd(a, b) === 1;
// Count them directly.
const totientByCounting = (n) => {
let count = 0;
for (let k = 1; k <= n; k++) if (coprime(k, n)) count++;
return count;
};
// Or derive it from the distinct primes dividing n.
const distinctPrimes = (n) => {
const out = [];
for (let d = 2; d * d <= n; d++) {
if (n % d !== 0) continue;
out.push(d);
while (n % d === 0) n /= d;
}
if (n > 1) out.push(n);
return out;
};
const totient = (n) => distinctPrimes(n).reduce((acc, p) => (acc / p) * (p - 1), n);
const consecutive = Array.from({ length: 20 }, (_, i) => coprime(i + 1, i + 2));
const gapOfTwo = Array.from({ length: 8 }, (_, i) => coprime(i + 1, i + 3));
console.log('8 and 15 :', coprime(8, 15), '<- neither is prime');
console.log('8 and 12 :', coprime(8, 12));
console.log('totient of 10, by counting:', totientByCounting(10), 'by formula:', totient(10));
console.log('totient of 1000 :', totientByCounting(1000), totient(1000));
console.log('n with n+1 :', consecutive.every(Boolean));
console.log('n with n+2 :', gapOfTwo);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('8 and 15 are coprime even though neither is prime', coprime(8, 15), true);
test('8 and 12 are not, they share 4', [coprime(8, 12), gcd(8, 12)], [false, 4]);
test('1 is coprime with everything, including itself', [coprime(1, 9), coprime(1, 1)], [true, true]);
test('0 is coprime with 1 and nothing else', [coprime(0, 1), coprime(0, 5)], [true, false]);
test('consecutive integers are always coprime', consecutive.every(Boolean), true);
test('but n and n + 2 only when n is odd', gapOfTwo, [true, false, true, false, true, false, true, false]);
test('the totient of a prime is p - 1', [totientByCounting(13), totient(97)], [12, 96]);
test('counting and the product formula agree, including at 1', [1, 9, 10, 12, 36, 1000].map(totient), [1, 9, 10, 12, 36, 1000].map(totientByCounting));
test('and the formula stays exact at 1000: 400 coprimes', totient(1000), 400);
Coprimality is a statement about a pair, not about either number: 8 and 15 are coprime while both are composite, and 8 and 12 are not while neither is prime. The only test is gcd === 1.
The totient's two forms are worth holding together. Counting is obvious and costs a GCD per candidate, so totientByCounting(1e9) is out of reach. The product form n * prod((p - 1) / p) costs one factorisation, and the order matters for the same reason as in exercise 38: written as (acc / p) * (p - 1) the division is exact because p divides acc, while acc * (p - 1) / p would inflate the intermediate before shrinking it again.
Common mistakes
- Thinking coprime means prime. 8 and 15 are both composite and still coprime. Only the GCD decides.
- Multiplying by
(1 - 1 / p). The fraction isn't exact in binary, so φ(36) comes out as 12.000000000000002. Divide by p, then multiply by p - 1. - Counting a repeated prime twice. 12 has the prime 2 twice, but the formula uses each distinct prime once. Divide each prime out fully before moving on.
Try it yourself
- List every number from 1 to 12 that is coprime with 12. You should get four of them.
- Show that for any prime p,
totient(p)isp - 1. Try 7, 11 and 97. - Write
isSimplest(top, bottom)that tells you whether a fraction can't be simplified any further.