How to use the gcd function from mathjs

Find comprehensive JavaScript mathjs.gcd code examples handpicked from public code repositorys.

mathjs.gcd is a function that returns the greatest common divisor of two or more integers.

165
166
167
168
169
170
171
172
173
174
fs.writeFileSync(__dirname + path.sep + filename, code);
console.log("Done: " + patterns.length + " patterns saved in " + filename);
console.log();

// Info about patterns length
const gcd = patternsDurations.length > 1 ? math.gcd(...patternsDurations) : patternsDurations[0];
console.log("Lower note: " + cvsNamesMap[cvsUniq[1]] + " (" + cvsUniq[1] + ")");
console.log("Higher note: " + cvsNamesMap[cvsUniq[cvsUniq.length - 1]] + " (" + cvsUniq[cvsUniq.length - 1] + ")");
console.log("Number of unique notes: " + cvsUniq.length + " (including pause)");
console.log("Duration of the shortest note: " + shortestNoteDuration);
fork icon27
star icon218
watch icon19

97
98
99
100
101
102
103
104
105
106
107
	})
}


function makeMaths(freqsArray) {
	return new Promise((resolve) => {
		const gcd = math.gcd(...freqsArray)
		const freqsDividedByGCD = freqsArray.map(freq => freq / gcd)
		const lcd = math.lcm(...freqsDividedByGCD)
		resolve(lcd)
	})
fork icon0
star icon6
watch icon1

+ 7 other calls in file

How does mathjs.gcd work?

mathjs.gcd function computes the greatest common divisor (GCD) of two or more numbers using the Euclidean algorithm. It repeatedly divides the greater number by the smaller number and keeps doing this until the remainder becomes zero. The last non-zero remainder is the GCD.

54
55
56
57
58
59
60
61
62
63
math.round(a) // round to nearest int
math.ceil(a); // round in positive direction
math.fix(a) // round towards zero

// factors & multiples
math.gcd(a, b) // greatest common denominator
math.lcm(a, b) // least common multiple

// stats
math.max(numbers);
fork icon0
star icon3
watch icon0

+ 6 other calls in file

-3
-2
-1
a = [12, 18, 24]
let gcd = math.gcd(a[0],a[1],a[2]);
console.log(gcd);
fork icon0
star icon0
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
4
const math = require("mathjs");

const result = math.gcd(24, 36, 48);
console.log(result); // output: 12

In this example, we first import the mathjs library and then use the math.gcd function to find the greatest common divisor of the numbers 24, 36, and 48. The result is 12, which is then printed to the console.