Trying to solve sequence problems without loops. This works with some triangle number maths.
function solution(num){ // find the nearest triangle number, use ceil to get to the current row const s = Math.ceil((Math.sqrt(8*num+1)-1)/2); // Gauss Summation to calculate the number of items in the "pyramid above" const t = ((s - 1) * (s))/2; return num - t; }
- function solution(num){
let times = 1;let count = 0;while(num > 0){count = numnum -= times;times++;}return count;- // find the nearest triangle number, use ceil to get to the current row
- const s = Math.ceil((Math.sqrt(8*num+1)-1)/2);
- // Gauss Summation to calculate the number of items in the "pyramid above"
- const t = ((s - 1) * (s))/2;
- return num - t;
- }
const { assert } = require("chai") function test(n, expected) { let actual = solution(n) it(`Expected ${expected}, got ${actual}`, () => { assert.strictEqual(actual, expected) }) } describe("basic tests", function(){ test(3,2); test(55,10); test(4,1); //200th triangle number test(20100, 200) test(20123, 23) })
- const { assert } = require("chai")
- function test(n, expected) {
- let actual = solution(n)
- it(`Expected ${expected}, got ${actual}`, () => {
- assert.strictEqual(actual, expected)
- })
- }
- describe("basic tests", function(){
- test(3,2);
- test(55,10);
- test(4,1);
- //200th triangle number
- test(20100, 200)
- test(20123, 23)
- })