Skip to main content
Fixed solution
Source Link
asgallant
  • 309
  • 1
  • 5

Broken, fix in progress

Javascript (ES6), 83108 bytes - fixed

x=>(y=a=>a++*a/2{t=[0],z=b=>y(~~t.f=t.forEach,i=j=k=0;for(Math;j<x;t[i]=j+=i++);t.sqrtf(2*b+a=>t.25)-f(b=>t.5)),n=zf(x)c=>a+b+c==x?k=[a,x-=nb,m=z(xc]:0),x-=m,[n,m,x]));return k}
x=>({
    t=[0],                               // useinitialize arrowan functionarray syntaxof triangle numbers
    y=a=>a++*at.f=t.forEach,                       /2/ copy forEach method into t.f,
                                         // calculatesaves thea a'thnet triangleof number4 bytes
    z=b=>y(~~(Math.sqrti=j=k=0;
    for(2*b+.25)-.5);j<x;t[i]=j+=i++),;               // calculatepopulate thet largestwith triangleall numbertriangle <numbers bthat
    n=z(x),                                     // getwe thecould largestpossibly triangleneed
 number < x
 t.f(   x-=n,                              // decrementloop xover byall nt
    m=z(x),    a=>t.f(                          // getloop theover largestall trianglet
 number < x
    x-=m,     b=>t.f(                      // loop over all t
                c=>a+b+c==x?k=[a,b,c]:0  // decrementif a+b+c = x, byset mk = [a,b,c], whateverelse isnoop
 left over in x is a triangle number
    [n,m,x]                             // returnusing ana arrayternary ofhere thesaves 31 trianglebyte numbersvs
 [n, m, x - n - m], via the comma operator (evaluates LtR, returns the last value)
)

How the math works

The nth triangle number is given by the formula n*(n+1)/2 (calculated here in the function a=>a++*a/2). In order to find the largest triangle number less than x, solve the inequality n*(n+1)/2 < x for the largest n, given by the floor of the quadratic solution for the largest root:

⌊(-b + √(b^2 - 4*a*c))/(2*a)⌋

plugging in a, b, and c from n*(n+1)/2 < x gives

⌊-0.5 + √(0.25 + 2x)⌋

which is solved for by

b=>y(~~(Math.sqrt(2*b+.25)-.5))

b=>                        // if statement
    y(                                     // getiterating theover trianglet numberlike atthis thewill indexfind givenall
 by the input
        ~~(                              // ~permutations isof bitwise[a,b,c] negatethat match, whichbut
 converts from float to int before negating (via something like Math.trunc)
                              // we will only return the last one found,
   // ~~ double bitwise negate is equivalent to Math.floor for positive numbers
            Math.sqrt(2*b + 0.25) - 0.5           // getwhich thehappens positiveto solutionbe tosorted thein quadraticdescending order
            )
        )
    );
    return k
}
const F = x=>(y=a=>a++*a/2{t=[0],z=b=>y(~~t.f=t.forEach,i=j=k=0;for(Math;j<x;t[i]=j+=i++);t.sqrtf(2*b+a=>t.25)-f(b=>t.5)),n=zf(x)c=>a+b+c==x?k=[a,x-=nb,m=z(xc]:0),x-=m,[n,m,x]));return k};

$('#output').hide();
$('#run').click(() => {
  const x = parseInt($('#input').val(), 10);
  if (x >= 0) {
    $('#input').val(x);
    const values = F(x);
    $('#values').text(values.join(', '));
    $('#output').show();
  }
  else {
    $('#output').hide();
    alert('You must enter a positive integer');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter a value: <input type="text" id="input" />
<br />
<button id="run">Get triangle numbers</button>
<br />
<span id="output">Triangle numbers are: <span id="values"></span></span>

Broken, fix in progress

Javascript (ES6), 83 bytes

x=>(y=a=>a++*a/2,z=b=>y(~~(Math.sqrt(2*b+.25)-.5)),n=z(x),x-=n,m=z(x),x-=m,[n,m,x])
x=>(                                   // use arrow function syntax
    y=a=>a++*a/2,                      // calculate the a'th triangle number
    z=b=>y(~~(Math.sqrt(2*b+.25)-.5)), // calculate the largest triangle number < b
    n=z(x),                            // get the largest triangle number < x
    x-=n,                              // decrement x by n
    m=z(x),                            // get the largest triangle number < x
    x-=m,                              // decrement x by m, whatever is left over in x is a triangle number
    [n,m,x]                            // return an array of the 3 triangle numbers [n, m, x - n - m], via the comma operator (evaluates LtR, returns the last value)
)

How the math works

The nth triangle number is given by the formula n*(n+1)/2 (calculated here in the function a=>a++*a/2). In order to find the largest triangle number less than x, solve the inequality n*(n+1)/2 < x for the largest n, given by the floor of the quadratic solution for the largest root:

⌊(-b + √(b^2 - 4*a*c))/(2*a)⌋

plugging in a, b, and c from n*(n+1)/2 < x gives

⌊-0.5 + √(0.25 + 2x)⌋

which is solved for by

b=>y(~~(Math.sqrt(2*b+.25)-.5))

b=>
    y(                                   // get the triangle number at the index given by the input
        ~~(                              // ~ is bitwise negate, which converts from float to int before negating (via something like Math.trunc)
                                         // ~~ double bitwise negate is equivalent to Math.floor for positive numbers
            Math.sqrt(2*b + 0.25) - 0.5  // get the positive solution to the quadratic
        )
    )
const F = x=>(y=a=>a++*a/2,z=b=>y(~~(Math.sqrt(2*b+.25)-.5)),n=z(x),x-=n,m=z(x),x-=m,[n,m,x]);

$('#output').hide();
$('#run').click(() => {
  const x = parseInt($('#input').val(), 10);
  if (x >= 0) {
    $('#input').val(x);
    const values = F(x);
    $('#values').text(values.join(', '));
    $('#output').show();
  }
  else {
    $('#output').hide();
    alert('You must enter a positive integer');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter a value: <input type="text" id="input" />
<br />
<button id="run">Get triangle numbers</button>
<br />
<span id="output">Triangle numbers are: <span id="values"></span></span>

Javascript (ES6), 108 bytes - fixed

x=>{t=[0],t.f=t.forEach,i=j=k=0;for(;j<x;t[i]=j+=i++);t.f(a=>t.f(b=>t.f(c=>a+b+c==x?k=[a,b,c]:0)));return k}
x=>{
    t=[0],                               // initialize an array of triangle numbers
    t.f=t.forEach,                       // copy forEach method into t.f,
                                         // saves a net of 4 bytes
    i=j=k=0;
    for(;j<x;t[i]=j+=i++);               // populate t with all triangle numbers that
                                         // we could possibly need
    t.f(                                 // loop over all t
        a=>t.f(                          // loop over all t
            b=>t.f(                      // loop over all t
                c=>a+b+c==x?k=[a,b,c]:0  // if a+b+c = x, set k = [a,b,c], else noop
                                         // using a ternary here saves 1 byte vs
                                         // if statement
                                         // iterating over t like this will find all
                                         // permutations of [a,b,c] that match, but
                                         // we will only return the last one found,
                                         // which happens to be sorted in descending order
            )
        )
    );
    return k
}
const F = x=>{t=[0],t.f=t.forEach,i=j=k=0;for(;j<x;t[i]=j+=i++);t.f(a=>t.f(b=>t.f(c=>a+b+c==x?k=[a,b,c]:0)));return k};

$('#output').hide();
$('#run').click(() => {
  const x = parseInt($('#input').val(), 10);
  if (x >= 0) {
    $('#input').val(x);
    const values = F(x);
    $('#values').text(values.join(', '));
    $('#output').show();
  }
  else {
    $('#output').hide();
    alert('You must enter a positive integer');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter a value: <input type="text" id="input" />
<br />
<button id="run">Get triangle numbers</button>
<br />
<span id="output">Triangle numbers are: <span id="values"></span></span>
marked solution as broken while a fix is in progress
Source Link
asgallant
  • 309
  • 1
  • 5

Broken, fix in progress

Javascript (ES6), 83 bytes

Javascript (ES6), 83 bytes

Broken, fix in progress

Javascript (ES6), 83 bytes

clarification
Source Link
asgallant
  • 309
  • 1
  • 5

The nth triangle number is given by the formula n*(n+1)/2 (calculated here in the function a=>a++*a/2). In order to find the largest triangle number less than x, solve the inequality n*(n+1)/2 < x for the largest n, given by the floor of the positive quadratic solution for the largest root:

The nth triangle number is given by the formula n*(n+1)/2 (calculated here in the function a=>a++*a/2). In order to find the largest triangle number less than x, solve the inequality n*(n+1)/2 < x for the largest n, given by the floor of the positive quadratic solution

The nth triangle number is given by the formula n*(n+1)/2 (calculated here in the function a=>a++*a/2). In order to find the largest triangle number less than x, solve the inequality n*(n+1)/2 < x for the largest n, given by the floor of the quadratic solution for the largest root:

added clarification to code comments
Source Link
asgallant
  • 309
  • 1
  • 5
Loading
Source Link
asgallant
  • 309
  • 1
  • 5
Loading