Skip to content

Commit

Permalink
implemented lcm and gcd algorithms
Browse files Browse the repository at this point in the history
  • Loading branch information
JulienR1 committed Feb 3, 2025
1 parent ca7443f commit 1c639a7
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 7 deletions.
33 changes: 30 additions & 3 deletions packages/web/src/lib/maths.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
import { describe, expect, test, } from "vitest";
import { gcd, lcm } from "./maths";

describe("maths", function() {
describe("gcd", function() {
test("should do something", function() {
expect(1).to.be.equal(1)
test("lcm", function() {
const tests = [
{ inputs: [1], expected: 1 },
{ inputs: [1, 2], expected: 2 },
{ inputs: [2, 3], expected: 6 },
{ inputs: [2, 4], expected: 4 },
{ inputs: [2, 3, 4], expected: 12 },
{ inputs: [1, 3, 5, 8], expected: 120 },
]

tests.forEach((test, i) => {
expect(lcm(test.inputs)).to.equal(test.expected, `tests[${i}]: expected ${test.inputs} to have ${test.expected} as lcm`);
})
})

test("gcd", function() {
const tests = [
{ inputs: [1], expected: 1 },
{ inputs: [1, 2], expected: 1 },
{ inputs: [2, 3], expected: 1 },
{ inputs: [2, 4], expected: 2 },
{ inputs: [2, 3, 4], expected: 1 },
{ inputs: [3, 6, 18], expected: 3 },
{ inputs: [12, 18], expected: 6 },
]

tests.forEach((test, i) => {
expect(gcd(test.inputs)).to.equal(test.expected, `tests[${i}]: expected ${test.inputs} to have ${test.expected} as gcd`);
})

})
})
44 changes: 40 additions & 4 deletions packages/web/src/lib/maths.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,49 @@
/***
* Greatest Common Divisor
*/
export function gcd(n: number): number {
return 0
export function gcd(n: number[]): number {
if (n.length === 1) {
return n[0]
}

// NOTE: See Euclidean algorithm
if (n.length === 2) {
let [a, b] = n
while (b !== 0) {
let t = b
b = a % b
a = t
}
return a
}

const stack = [...n]
while (stack.length >= 2) {
let a = stack.pop()!
let b = stack.pop()!
stack.push(gcd([a, b]))
}
return stack[0]
}

/**
* Lowest Common Multiple
*/
export function lcm(n: number): number {
return 0
export function lcm(n: number[]): number {
if (n.length === 0) {
return 0
}

if (n.length <= 2) {
const product = n.reduce((p, curr) => p * curr, 1)
return product / gcd(n)
}

const stack = [...n]
while (stack.length >= 2) {
let a = stack.pop()!
let b = stack.pop()!
stack.push(lcm([a, b]))
}
return stack[0]
}

0 comments on commit 1c639a7

Please sign in to comment.