Ad

Trying to solve sequence problems without loops. This works with some triangle number maths.

Code
Diff
  • 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 = num
    • num -= 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;
    • }