Skip to content

Instantly share code, notes, and snippets.

@kayac-chang
Created July 5, 2023 13:09
Show Gist options
  • Save kayac-chang/eb8903bf0e0aba0af230cbd726b0cf25 to your computer and use it in GitHub Desktop.
Save kayac-chang/eb8903bf0e0aba0af230cbd726b0cf25 to your computer and use it in GitHub Desktop.
recur to loop
import { test, expect, describe } from "vitest";
function recur(n: number, cur?: number): number {
if (!cur) {
cur = 0;
}
if (n < 2) {
throw new Error("Invalid input");
}
if (n === 2) {
return 1 / n + cur;
}
return recur(n - 1, cur + 1 / (n * (n - 1)));
}
function loop(n: number): number {
let cur = 0;
for (let i = n; i > 2; i--) {
cur += 1 / (i * (i - 1));
}
cur += 1 / 2;
return cur;
}
describe("test recur", () => {
test("n = 2", () => {
expect(loop(2)).toBe(recur(2));
});
test("n = 3", () => {
expect(loop(3)).toBe(recur(3));
});
test("n = 4", () => {
expect(loop(4)).toBe(recur(4));
});
test("n = 5", () => {
expect(loop(5)).toBe(recur(5));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment