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>