From 880efac15bba02e7c3f61a0fe4eead3e0040b5ba Mon Sep 17 00:00:00 2001 From: Glen Whitney Date: Tue, 2 Aug 2022 10:32:06 -0700 Subject: [PATCH] feat(gcd,lcm): Allow arbitrarily many arguments And add an 'associate' predicate for two complex numbers to check the results --- src/complex/associate.mjs | 17 +++++++++++++++++ src/complex/native.mjs | 1 + src/generic/arithmetic.mjs | 1 + src/generic/lcm.mjs | 3 +++ test/_pocomath.mjs | 9 +++++++++ 5 files changed, 31 insertions(+) create mode 100644 src/complex/associate.mjs diff --git a/src/complex/associate.mjs b/src/complex/associate.mjs new file mode 100644 index 0000000..c6fab9e --- /dev/null +++ b/src/complex/associate.mjs @@ -0,0 +1,17 @@ +export * from './Types/Complex.mjs' + +/* Returns true if w is z multiplied by a complex unit */ +export const associate = { + 'Complex,Complex': ({ + 'multiply(Complex,Complex)': times, + 'equal(Complex,Complex)': eq, + zero, + one, + complex, + 'negate(Complex)': neg + }) => (w,z) => { + if (eq(w,z) || eq(w,neg(z))) return true + const ti = times(z, complex(zero(z.re), one(z.im))) + return eq(w,ti) || eq(w,neg(ti)) + } +} diff --git a/src/complex/native.mjs b/src/complex/native.mjs index bea1db8..4f63c8f 100644 --- a/src/complex/native.mjs +++ b/src/complex/native.mjs @@ -3,6 +3,7 @@ export * from './Types/Complex.mjs' export {abs} from './abs.mjs' export {absquare} from './absquare.mjs' export {add} from './add.mjs' +export {associate} from './associate.mjs' export {conjugate} from './conjugate.mjs' export {complex} from './complex.mjs' export {equal} from './equal.mjs' diff --git a/src/generic/arithmetic.mjs b/src/generic/arithmetic.mjs index f6abd23..04948df 100644 --- a/src/generic/arithmetic.mjs +++ b/src/generic/arithmetic.mjs @@ -3,6 +3,7 @@ import {reducingOperation} from './reducingOperation.mjs' export * from './Types/generic.mjs' export const add = reducingOperation +export const gcd = reducingOperation export {lcm} from './lcm.mjs' export {mean} from './mean.mjs' export {mod} from './mod.mjs' diff --git a/src/generic/lcm.mjs b/src/generic/lcm.mjs index adc3dfb..04e78b5 100644 --- a/src/generic/lcm.mjs +++ b/src/generic/lcm.mjs @@ -1,3 +1,5 @@ +import {reducingOperation} from './reducingOperation.mjs' + export const lcm = { 'T,T': ({ 'multiply(T,T)': multT, @@ -5,3 +7,4 @@ export const lcm = { 'gcd(T,T)': gcdT }) => (a,b) => multT(quotT(a, gcdT(a,b)), b) } +Object.assign(lcm, reducingOperation) diff --git a/test/_pocomath.mjs b/test/_pocomath.mjs index 18643b0..1d7d1e9 100644 --- a/test/_pocomath.mjs +++ b/test/_pocomath.mjs @@ -103,4 +103,13 @@ describe('The default full pocomath instance "math"', () => { assert.strictEqual(math.choose(21n, 2n), 210n) }) + it('calculates multi-way gcds and lcms', () => { + assert.strictEqual(math.gcd(30,105,42), 3) + assert.ok( + math.associate( + math.lcm( + math.complex(2n,1n), math.complex(1n,1n), math.complex(0n,1n)), + math.complex(1n,3n))) + }) + })