loading...

Discussion on: Daily Challenge #78 - Number of Proper Fractions with Denominator d

Collapse
jeffong profile image
Jeff Ong

A Javascript solution:

const gcd = (n, d) => {
 return d === 0 ? n : gcd(d, n % d);
}

const proper_fractions = (d) => {
    if (d === 0 || d === 1) {
        return 0;
    }
    if (d === 2) {
        return 1;
    }
    let count = 0;
    let n = 0;
    while (n < d) {
        if (gcd(n, d) === 1) {
            count++;
        }
        n++;
    }
    return count;
}

console.log('Test cases');
console.log(`if d = 1, result: ${proper_fractions(1)}`);
console.log(`if d = 2,  result: ${proper_fractions(2)}`);
console.log(`if d = 5,  result: ${proper_fractions(5)}`);
console.log(`if d = 15, result: ${proper_fractions(15)}`);
console.log(`if d = 25, result: ${proper_fractions(25)}`);

Test cases:

if d = 1, result: 0
if d = 2,  result: 1
if d = 5,  result: 4
if d = 15, result: 8
if d = 25, result: 20

This is a pretty straight-forward solution using a counter. You can run this in vscode terminal as node [file-name].js