Triangular Dependencies

25

0

A triangular number is a number that is the sum of n natural numbers from 1 to n. For example 1 + 2 + 3 + 4 = 10 so 10 is a triangular number.

Given a positive integer (0 < n <= 10000) as input (can be taken as an integer, or as a string), return the smallest possible triangular number that can be added to the input to create another triangular number.

For example given input 26, adding 10 results in 36, which is also a triangular number. There are no triangular numbers smaller than 10 that can be added to 26 to create another triangular number, so 10 is the correct result in this case.

0 is a triangular number, therefore if the input is itself a triangular number, the output should be 0

Testcases

Cases are given in the format input -> output (resulting triangular number)

0     -> 0   (0)
4     -> 6   (10)
5     -> 1   (6)
7     -> 3   (10)
8     -> 28  (36)
10    -> 0   (10)
24    -> 21  (45)
25    -> 3   (28)
26    -> 10  (36)
34    -> 21  (55)
10000 -> 153 (10153)

Scoring

This is so fewest bytes in each language wins!

Skidsdev

Posted 2017-06-29T10:24:54.330

Reputation: 9 656

Isn't it 26 -> 2? – Okx – 2017-06-29T10:29:48.033

@Okx I made the same mistake, you need to find a triangular number to add to the current one to make another triangular number. – Martin Ender – 2017-06-29T10:31:47.197

2Related. (borderline duplicate) – Martin Ender – 2017-06-29T10:31:58.500

Answers

21

Java 8, 58 57 bytes

n->{int i=0,m=0;while(n!=0)n+=n<0?++i:--m;return-~i*i/2;}

Online test suite

Thanks to Dennis for a 1-byte saving.

Peter Taylor

Posted 2017-06-29T10:24:54.330

Reputation: 41 901

6Now this is Java, golfed! :) – Olivier Grégoire – 2017-06-29T13:39:14.730

I count 58 bytes, you seem to have included a trailing newline in the byte-count. – Okx – 2017-06-29T14:31:38.803

Is order of operations guaranteed on the "i*++i" part? I could see this maybe not working on some JVM implementations. Nice solution regardless. – Computronium – 2017-06-29T14:37:06.197

4

@Computronium, order of operations is guaranteed by the Java Language Specification. Java deliberately avoids some of the weaknesses of C.

– Peter Taylor – 2017-06-29T14:39:58.100

2

@Computronium https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

– JollyJoker – 2017-06-29T14:40:15.850

2return-~i*i/2; saves a byte. – Dennis – 2017-06-30T06:38:19.463

Can't you use n->r->{int i=0,m=0;while(n!=0)n+=n<0?++i:--m;r=-~i*i/2;} to save a byte? – Okx – 2017-06-30T11:51:36.773

@Okx, really? I'm not sure how you'd invoke that in such a way that the caller gets the updated value of r; and while I admit that I haven't followed every one of the dozens of proposals for standard I/O, I'm not aware of one which would allow it. – Peter Taylor – 2017-06-30T12:01:42.753

@PeterTaylor https://codegolf.meta.stackexchange.com/a/4942/26600 you may even be able to save more bytes by using n->{int i=0,m=0;while(n!=0)n+=n<0?++i:--m;n=-~i*i/2;

– Okx – 2017-06-30T12:57:11.760

1@Okx Java is pass-by-value for primitive types and pass-by-reference for objects (including arrays). If you want to actually output in the same variable, you have to be in a pass-by-reference context (explicitly said in your link). The only way I see to pass-by-reference that could work is to pass an int[] instead of an int as argument. But that means dealing with arrays later on. This could work: x->{int i=0,m=0,n=x[0];while(n!=0)n+=n<0?++i:--m;x[0]=-~i*i/2;}, but it's 63 bytes. – Olivier Grégoire – 2017-06-30T13:49:17.857

7

Java (OpenJDK 8), 83 bytes

n->{int m=0,a=n,b;for(;a-->0;)for(b=0;b<=n;)m=2*n+b*~b++==a*~a?a*a+a:m;return m/2;}

Try it online!

Credits

Olivier Grégoire

Posted 2017-06-29T10:24:54.330

Reputation: 10 647

1

Nice answer (as always..). Hadn't noticed there was already a Java answer when I posted mine.. Mine was initially shorter, but not anymore it seems. :)

– Kevin Cruijssen – 2017-06-29T11:20:03.557

Thanks! Yeah, my first answer was really redundant. I fixed it and made it more mathy, though more processor-greedy as well. I'll check yours in a sec! – Olivier Grégoire – 2017-06-29T11:24:38.400

I still don't understand what is happening here. Why is it working? You are replacing m every time, so what's the point? – V. Courtois – 2017-06-29T13:53:06.757

2@V.Courtois The question asks for the smallest m. So I go from a down to 0. "but you're assigning maybe 100 times the same value a*a+a to m in the b-loop", yep, I don't need to do it 100 times, but I'm gaining bytes by not breaking the b-loop earlier. – Olivier Grégoire – 2017-06-29T13:55:08.057

I see @OlivierGrégoire. So that's anti-efficient on purpose :D – V. Courtois – 2017-06-29T13:57:46.927

@V.Courtois exactly! – Olivier Grégoire – 2017-06-29T13:58:45.983

7

MATL, 13 12 bytes

1 byte removed using an idea (set intersection) from Emigna's 05AB1E answer

Q:qYstG-X&X<

Try it online!

Explanation

Let t(n) = 1 + 2 + ··· + n denote the n-th triangular number.

The code exploits the fact that, given n, the solution is upper-bounded by t(n-1). To see this, observe that t(n-1) + n equals t(n) and so it is a triangular number.

Consider input 8 as an example.

Q:q   % Input n implicitly. Push [0 1 2 ... n]
      % STACK: [0 1 2 3 4 5 6 7 8]
Ys    % Cumulative sum
      % STACK: [0 1 3 6 10 15 21 28 36]
t     % Duplicate
      % STACK: [0 1 3 6 10 15 21 28 36], [0 1 3 6 10 15 21 28 36]
G-    % Subtract input, element-wise
      % STACK: [0 1 3 6 10 15 21 28 36], [-8 -7 -5 -2  2  7 13 20 28]
X&    % Set intersection
      % STACK: 28
X<    % Minimum of array (in case there are several solutions). Implicit display
      % STACK: 28

Luis Mendo

Posted 2017-06-29T10:24:54.330

Reputation: 87 464

Can you remove the leading Q by your argument about boundedness? – Giuseppe – 2018-01-10T17:05:35.717

@Giuseppe No, that fails for input 8. When the output equals the bound t(n-1), the code obtains it as t(n)-n. So t(n) is necessary. Thanks for the idea anyway! – Luis Mendo – 2018-01-10T17:14:57.607

5

Mathematica, 46 bytes

Min[Select[(d=Divisors[2#])-2#/d,OddQ]^2-1]/8&

alephalpha

Posted 2017-06-29T10:24:54.330

Reputation: 23 988

4

Neim, 12 9 bytes

tSΛt)0

This takes too long to compute (but works given infinite time and memory), so in the link I only generate the first 143 triangular numbers - using £, which is enough to handle an input of 10,000, but not enough to time out.

Warning: this may not work in future versions. If so, substitute £ for 143

Explanation:

t                 Infinite list of triangular numbers
 [ ]             Select the first  v  numbers
 [£ ]                              143
     S           Subtract the input from each element
       Λ  )       Only keep elements that are
        t          triangular
           0     Get the value closest to 0 - prioritising the higher number if tie

Try it!

Okx

Posted 2017-06-29T10:24:54.330

Reputation: 15 025

How are the first 143 triangle numbers enough for any input between 0 and 10000? With the input 9998, the expected result is 3118753, which is way above the 143rd triangle number (which is `10296). – Olivier Grégoire – 2017-06-29T12:36:28.417

@OlivierGrégoire because This takes too long to compute (but works given infinite time and memory) – Stephen – 2017-06-29T12:56:44.383

Thank you @StepHen but that's not what I said. What I implied is that the sentence "the first 143 triangular numbers [are] enough to handle an input of 10,000" is wrong. I haven't done the maths, but I believe that you should need around 10000 (give or take) triangle numbers to handle the cases up to 10000. – Olivier Grégoire – 2017-06-29T13:01:28.300

@OlivierGrégoire I stated that it is enough to handle an input of 10,000, but not any number less than it. Feel free to change £ to a higher number, such as 200. – Okx – 2017-06-29T14:23:53.743

@Okx Okay, I didn't understand it like that when I first read, thank you for taking the time to explain :) – Olivier Grégoire – 2017-06-29T14:26:30.847

4

PHP, 45 bytes

for(;!$$t;$t+=++$i)${$argn+$t}=~+$t;echo~$$t;

Try it online!

Is the shorter variant of for(;!$r[$t];$t+=++$i)$r[$argn+$t]=~+$t;echo~$r[$t];

Expanded

for(;!$$t;  # stop if a triangular number exists where input plus triangular number is a triangular number
$t+=++$i) # make the next triangular number
  ${$argn+$t}=~+$t; # build variable $4,$5,$7,$10,... for input 4 
echo~$$t; # Output result 

PHP, 53 bytes

for(;$d=$t<=>$n+$argn;)~$d?$n+=++$k:$t+=++$i;echo+$n;

Try it online!

Use the new spaceship operator in PHP 7

Expanded

for(;$d=$t<=>$n+$argn;) # stop if triangular number is equal to input plus triangular number 
  ~$d
    ?$n+=++$k  # raise additional triangular number
    :$t+=++$i; # raise triangular number sum
echo+$n; # Output and cast variable to integer in case of zero

PHP, 55 bytes

for(;fmod(sqrt(8*($t+$argn)+1),2)!=1;)$t+=++$i;echo+$t;

Try it online!

Jörg Hülsermann

Posted 2017-06-29T10:24:54.330

Reputation: 13 026

4

Java 8, 110 102 100 93 92 bytes

n->{int r=0;for(;t(r)<-t(n+r);r++);return r;}int t(int n){for(int j=0;n>0;n-=++j);return n;}

-2 bytes thanks to @PeterTaylor.
-7 bytes thanks to @JollyJoker.
-1 byte thanks to @ceilingcat.

Explanation:

Try it online.

n->{                  // Method with integer as parameter and return-type
  int r=0;            //  Result-integer (starting at 0)
  for(;t(r)<-t(n+r);  //  Loop as long as neither `r` nor `n+r` is a triangular number
    r++);             //   And increase `r` by 1 after every iteration
  return r;}          //  Return the result of the loop

int t(int n){         // Separate method with integer as parameter and return-type
                      // This method will return 0 if the input is a triangular number
  for(int i=0;n>0;)   //  Loop as long as the input `n` is larger than 0
    n-=++j;           //   Decrease `n` by `j` every iteration, after we've raised `j` by 1
  return n;}          //  Return `n`, which is now either 0 or below 0

Kevin Cruijssen

Posted 2017-06-29T10:24:54.330

Reputation: 67 575

1Easiest to read of the Java solutions :) – JollyJoker – 2017-06-29T15:09:49.287

@JollyJoker Maybe that's why it's the longest. ;) Or is it because of my added explanation? – Kevin Cruijssen – 2017-06-29T18:21:19.950

Nah, I was thinking about the code. I probably spent 15 mins figuring out how Peter Taylor's solution works. Yours is clear even without the comments. – JollyJoker – 2017-06-30T07:29:53.220

3

Brachylog, 17 15 bytes

⟦{a₀+}ᶠ⊇Ċ-ṅ?∧Ċh

Try it online!

Explanation

⟦                  [0, …, Input]
 {   }ᶠ            Find all…
  a₀+                …Sums of prefixes (i.e. triangular numbers)
       ⊇Ċ          Take an ordered subset of two elements
         -ṅ?       Subtracting those elements results in -(Input)
            ∧Ċh    Output is the first element of that subset

Fatalize

Posted 2017-06-29T10:24:54.330

Reputation: 32 976

3

Japt, 24 23 16 15 bytes

ò å+
m!nNg)æ!øU

Test it

1 byte saved thanks to ETH


Explanation

    :Implicit input of integer U.
ò   :Create an array of integers from 0 to U, inclusive.
å+  :Cumulatively reduce by summing. Result is implicitly assigned to variable V.
m   :Map over U.
!n  :From the current element subtract...
Ng  :  The first element in the array of inputs (the original value of U).
æ   :Get the first element that returns true when...
!øU :  Checking if U contains it.
    :Implicit output of resulting integer.

Shaggy

Posted 2017-06-29T10:24:54.330

Reputation: 24 623

I think you can save a byte with æ!øV. Other than that, looks great :-) – ETHproductions – 2017-06-30T22:27:25.190

3

Octave, 38 36 bytes

2 bytes off thanks to @Giuseppe!

@(n)(x=cumsum(0:n))(any(x+n==x'))(1)

Anonymous function that uses almost the same approach as my MATL answer.

Try it online!

Luis Mendo

Posted 2017-06-29T10:24:54.330

Reputation: 87 464

3

Jelly, 8 bytes

0r+\ðf_Ḣ

Try it online!

How it works

0r+\ðf_Ḣ  Main link. Argument: n

0r        Build [0, ..., n].
  +\      Take the cumulative sum, generating A := [T(0), ..., T(n)].
    ð     Begin a dyadic chain with left argument A and right argument n.
      _   Compute A - n, i.e., subtract n from each number in A.
     f    Filter; keep only numbers of A that appear in A - n.
       Ḣ  Head; take the first result.

Dennis

Posted 2017-06-29T10:24:54.330

Reputation: 196 637

3

Python 2, 59 bytes

lambda n:min((r-2*n/r)**2/8for r in range(1,2*n,2)if n%r<1)

Try it online!

This uses the following characterization of the triangular numbers t than can be added to n to get a triangular number:

8*t+1 = (r-2*s)^2 for divisor pairs (r,s) with r*s==n and r odd.

The code takes the minimum of all such triangular numbers.

xnor

Posted 2017-06-29T10:24:54.330

Reputation: 115 687

2

Mathematica, 62 bytes

(s=Min@Abs[m/.Solve[2#==(n-m)(n+m+1),{n,m},Integers]])(s+1)/2&

J42161217

Posted 2017-06-29T10:24:54.330

Reputation: 15 931

I don't know Mathematica, but would Solve[2*#==m(m+1)-n(n+1) be shorter (if it works)? – user41805 – 2017-06-29T10:43:11.377

yes, I just posted my answer and trying to golf it right now – J42161217 – 2017-06-29T10:44:35.127

2

JavaScript (ES7), 46 44 bytes

f=(n,x=r=0)=>(8*(n+x)+1)**.5%1?f(n,x+=++r):x

Try it

o.innerText=(
f=(n,x=r=0)=>(8*(n+x)+1)**.5%1?f(n,x+=++r):x
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
<input id=i type=number><pre id=o>

Shaggy

Posted 2017-06-29T10:24:54.330

Reputation: 24 623

1Would r=x=0 work? – user41805 – 2017-06-29T11:07:38.293

Sadly not, @KritixiLithos. – Shaggy – 2017-06-29T11:10:17.973

2

Python 2, 78 71 70 bytes

Seven bytes saved, thanx to ovs and theespinosa

One more byte saved due to the remark of neil, x+9 is suffisant and checked for all natural numbers 0 <= n <= 10000. It was also verified for x+1 instead of x+9, it works also.

x=input()
I={n*-~n/2for n in range(x+1)}
print min(I&{i-x for i in I})

Try it online!

mdahmoune

Posted 2017-06-29T10:24:54.330

Reputation: 2 605

2You can use n*-~n/2 instead of n*(n+1)/2 – ovs – 2017-06-29T12:00:51.710

2Would range(x+9) work? – Neil – 2017-06-29T12:16:03.627

2You can use {n*(n+1)/2for n in range(999)} instead of explicit set and also use {} instead of set in the third line – TheEspinosa – 2017-06-29T12:52:28.490

2

05AB1E, 12 bytes

ÝηOãD€Æ¹QϬ¤

Uses the 05AB1E encoding. Try it online!

Adnan

Posted 2017-06-29T10:24:54.330

Reputation: 41 965

2

JavaScript (ES6), 43 42 bytes

f=(n,a=s=0)=>n?f(n+=n>0?--s:++a,a):a*++a/2
<input type=number min=0 value=0 oninput=o.textContent=f(+this.value)><pre id=o>0

Edit: Saved 1 byte thanks to @PeterTaylor.

Neil

Posted 2017-06-29T10:24:54.330

Reputation: 95 035

Setting a global variable is a hideous abuse of a default parameter. +1. But FWIW you can save a further byte by replacing -++s with --s, as I did in my independently derived but quite similar Java version. (Addendum: you also need to change the test to n>0). – Peter Taylor – 2017-06-29T13:39:47.953

@PeterTaylor Huh, so the n>s check was a red herring all along! – Neil – 2017-06-29T16:36:41.480

Works not for 8192 – Jörg Hülsermann – 2017-06-29T19:24:16.360

@JörgHülsermann If you're referring to the snippet, then your browser's stack size may not be large enough, or you may need a browser with experimental tail call optimisation. Alternatively, if you're using NodeJS for testing, use node --stack_size= to increase its stack size. – Neil – 2017-06-29T20:15:47.687

2

Python 3, 60 44 bytes

f=lambda n,k=1:(8*n+1)**.5%1and f(n+k,k+1)+k

Thanks to @xnor for a suggestion that saved 16 bytes!

Try it online!

Background

Let n be a non-negative integer. If n is the kth triangular number, we have

condition

which means there will be a natural solution if and only if 1 + 8n is an odd, perfect square. Clearly, checking the parity of 1 + 8n is not required.

How it works

The recursive function n accepts a single, non-negative integer as argument. When called with a single argument, k defaults to 1.

First, (8*n+1)**.5%1 tests if n is a triangular number: if (and only if) it is, (8*n+1)**.5 will yield an integer, so the residue from the division by 1 will yield 0.

If the modulus is 0, the and condition will fail, causing f to return 0. If this happens in the initial call to f, note that this is the correct output since n is already triangular.

If the modulus is positive, the and condition holds and f(n+k,k+1)+k gets executed. This calls f again, incrementing n by k and k by 1, then adds k to the result.

When f(n0, k0) finally returns 0, we back out of the recursion. The first argument in the first call was n, the second one n + 1, the third one n + 1 + 2, until finally n0 = n + 1 + … k0-1. Note that n0 - n is a triangular number.

Likewise, all these integers will be added to the innermost return value (0), so the result of the intial call f(n) is n0 - n, as desired.

Dennis

Posted 2017-06-29T10:24:54.330

Reputation: 196 637

If you increment n in recursing as well, you can write n rather than (n+k). – xnor – 2017-06-29T17:07:44.913

Or better, search triangular numbers directly.

– xnor – 2017-06-29T17:19:42.400

Wow, that's a lot nicer than what I was trying. – xnor – 2017-06-29T17:54:20.417

2

C# (.NET Core), 291 281 bytes

class p{static int Main(string[]I){string d="0",s=I[0];int c=1,j,k;for(;;){j=k=0;string[]D=d.Split(' '),S=s.Split(' ');for(;j<D.Length;j++)for(;k<S.Length;k++)if(D[j]==S[k])return int.Parse(D[k]);j=int.Parse(D[0])+c++;d=d.Insert(0,$"{j} ");s=s.Insert(0,$"{j+int.Parse(I[0])} ");}}}

Try it online! Program that takes a string as input and outputs through Exit Code.

Saved 10 Bytes thanks to Kevin Cruijssen

Kamil Drakari

Posted 2017-06-29T10:24:54.330

Reputation: 3 461

1Hi, welcome to PPCG! You don't need a full program unless the challenge states otherwise. The default is program/function, so a lambda is allowed as well in C#. But if you want to use program, you can golf some things in your current code: class p{static int Main(string[]I){string d="0",s=I[0];int c=1,j,k;for(;;){j=k=0;string[]D=d.Split(' '),S=s.Split(' ');for(;j<D.Length;j++)for(;k<S.Length;k++)if(D[j]==S[k])return int.Parse(D[k]);j=int.Parse(D[0])+c++;d=d.Insert(0,$"{j} ");s=s.Insert(0,$"{j+int.Parse(I[0])} ");}}} (281 bytes) – Kevin Cruijssen – 2017-06-30T07:44:50.523

@KevinCruijssen Thanks for the advice! using for(;;) to make an infinite loop is a nice bump, and I'll make sure to think more carefully about whether using var is actually more efficient than using an explicit type but combining the declarations, and I guess be more diligent in removing unnecessary brackets. As for the program vs. function, I started with a lambda but couldn't get it to run in TIO. I know a TIO link isn't actually necessary, but it's something I like to see in others' answers so I wanted at least something similar in my own. – Kamil Drakari – 2017-06-30T13:24:07.983

I'm also not very good in C# lambdas tbh, I usually codegolf in Java. But I think this should be correct. (252 bytes). Also, in case you haven't seen it yet: Tips for code-golfing in C# and Tips for golfing in <all languages> might be interesting to read through. Again welcome, and +1 from me. Nice first answer. Enjoy your stay. :)

– Kevin Cruijssen – 2017-06-30T13:45:38.713

1

Dyalog APL, 19 bytes

6 bytes saved thanks to @KritixiLithos

{⊃o/⍨o∊⍨⍵+o←0,+\⍳⍵}

Try it online!

How?

o←0,+\⍳⍵ - assign o the first triangular numbers

o/⍨ - filter o by

o∊⍨⍵+o - triangular numbers that summed with produce triangulars

- and take the first

Uriel

Posted 2017-06-29T10:24:54.330

Reputation: 11 708

+\⍳⍵ should work instead of what you are using to generate the triangular numbers. – user41805 – 2017-06-29T10:46:39.947

I think works instead of ⌊/ – user41805 – 2017-06-29T10:58:31.397

1

Pari/GP, 54 bytes

n->vecmin([y^2-1|y<-[2*n/d-d|d<-divisors(2*n)],y%2])/8

Try it online!

alephalpha

Posted 2017-06-29T10:24:54.330

Reputation: 23 988

1

05AB1E, 8 bytes

ÝηODI-Ãн

Try it online! or as a Test suite

Explanation

Ý          # range [0 ... input]
 η         # prefixes
  O        # sum each
   D       # duplicate
    I-     # subtract input from each
      Ã    # keep only the elements in the first list that also exist in the second list
       н   # get the first (smallest)

Emigna

Posted 2017-06-29T10:24:54.330

Reputation: 50 798

1

R, 46 44 43 41 bytes

function(x,y=cumsum(0:x))y[(x+y)%in%y][1]

Try it online!

An anonymous function with one mandatory argument, x; computes first x+1 triangular numbers as an optional argument to golf out a few curly braces. I used choose before I saw Luis Mendo's Octave answer.

I shaved off a few bytes of Luis Mendo's answer but forgot to use the same idea in my answer.

Giuseppe

Posted 2017-06-29T10:24:54.330

Reputation: 21 077

1

Add++, 68 bytes

L,RBFEREsECAAx$pBcB_B]VARBFEREsB]GEi$pGBcB*A8*1+.5^1%!!@A!@*b]EZBF#@

Try it online!, or see the test suite!

Even Java is beating me. I really need to add some set commands to Add++

How it works

L,    - Create a lambda function
      - Example argument:  8
  R   - Range;     STACK = [[1 2 3 4 5 6 7 8]]
  BF  - Flatten;   STACK = [1 2 3 4 5 6 7 8]
  ER  - Range;     STACK = [[1] [1 2] ... [1 2 3 4 5 6 7 8]
  Es  - Sum;       STACK = [1 3 6 10 15 21 28 36]
  EC  - Collect;   STACK = [[1 3 6 10 15 21 28 36]]
  A   - Argument;  STACK = [[1 3 6 10 15 21 28 36] 8]
  A   - Argument;  STACK = [[1 3 6 10 15 21 28 36] 8 8]
  x   - Repeat;    STACK = [[1 3 6 10 15 21 28 36] 8 [8 8 8 8 8 8 8 8]]
  $p  - Remove;    STACK = [[1 3 6 10 15 21 28 36] [8 8 8 8 8 8 8 8]]
  Bc  - Zip;       STACK = [[1 8] [3 8] [6 8] [10 8] [15 8] [21 8] [28 8] [36 8]]
  B_  - Deltas;    STACK = [-7 -5 -2 2 7 13 20 28]
  B]  - Wrap;      STACK = [[-7 -5 -2 2 7 13 20 28]]
  V   - Save;      STACK = []
  A   - Argument;  STACK = [8]
  R   - Range;     STACK = [[1 2 3 4 5 6 7 8]]
  BF  - Flatten;   STACK = [1 2 3 4 5 6 7 8]
  ER  - Range;     STACK = [[1] [1 2] ... [1 2 3 4 5 6 7 8]]
  Es  - Sum;       STACK = [1 3 6 10 15 21 28 36]
  B]  - Wrap;      STACK = [[1 3 6 10 15 21 28 36]]
  G   - Retrieve;  STACK = [[1 3 6 10 15 21 28 36] [-7 -5 -2 2 7 13 20 28]]
  Ei  - Contains;  STACK = [[1 3 6 10 15 21 28 36] [0 0 0 0 0 0 0 1]]
  $p  - Remove;    STACK = [[0 0 0 0 0 0 0 1]]
  G   - Retrieve;  STACK = [[0 0 0 0 0 0 0 1] [-7 -5 -2 2 7 13 20 28]]
  Bc  - Zip;       STACK = [[0 -7] [0 -5] [0 -2] [0 2] [0 7] [0 13] [0 20] [1 28]]
  B*  - Products;  STACK = [0 0 0 0 0 0 0 28]
  A   - Argument;  STACK = [0 0 0 0 0 0 0 28 8]
  8*  - Times 8;   STACK = [0 0 0 0 0 0 0 28 64]
  1+  - Increment; STACK = [0 0 0 0 0 0 0 28 65]
  .5^ - Root;      STACK = [0 0 0 0 0 0 0 28 8.1]
  1%  - Frac part; STACK = [0 0 0 0 0 0 0 28 0.1]
  !!  - To bool;   STACK = [0 0 0 0 0 0 0 28 1]
  @   - Reverse;   STACK = [1 28 0 0 0 0 0 0 0]
  A   - Argument;  STACK = [1 28 0 0 0 0 0 0 0 8] 
  !   - Not;       STACK = [1 28 0 0 0 0 0 0 0 0]
  @   - Reverse;   STACK = [0 0 0 0 0 0 0 0 28 1]
  *   - Multiply;  STACK = [0 0 0 0 0 0 0 0 28]
  b]  - Wrap;      STACK = [0 0 0 0 0 0 0 0 [28]]
  EZ  - Unzero;    STACK = [[28]]
  BF  - Flatten;   STACK = [28]
  #   - Sort;      STACK = [28]
  @   - Reverse;   STACK = [28]

caird coinheringaahing

Posted 2017-06-29T10:24:54.330

Reputation: 13 702

1

Haskell, 56 bytes

f x|e<-(`elem`scanl1(+)[0..x])=[n|n<-[0..],e n,e$x+n]!!0

Try it online!

ბიმო

Posted 2017-06-29T10:24:54.330

Reputation: 15 345

0

Python 2, 83 81 bytes

  • @Felipe Nardi Batista saved 2 bytes.
lambda n:min(x for x in i(n)if n+x in i(n))
i=lambda n:[i*-~i/2for i in range(n)]

Try it online!

officialaimm

Posted 2017-06-29T10:24:54.330

Reputation: 2 739

0

Jelly, 18 bytes

0rRS$€ċ
0ð,+Ç€Ạð1#

Try it online!

Erik the Outgolfer

Posted 2017-06-29T10:24:54.330

Reputation: 38 134

0

APL (Dyalog Classic), 16 14 bytes

(⊃0∘,∩⊢-≢)+\∘⍳

Try it online!

TwiNight

Posted 2017-06-29T10:24:54.330

Reputation: 4 187

0

Clojure, 74 bytes

#(nth(for[t[(reductions +(range))]i t :when((set(take 1e5 t))(+ i %))]i)0)
#(nth(for[R[reductions]i(R + %(range)):when((set(R - i(range 1e5)))0)]i)0)

Pick your favourite :) Loops might be shorter...

NikoNyrh

Posted 2017-06-29T10:24:54.330

Reputation: 2 361

0

Python 2, 82 bytes

f=lambda n,R=[1]:n-sum(R)and f(n,[R+[R[-1]+1],R[1:]][sum(R)>n])or sum(range(R[0]))

Try it online

This was created by modifying this answer from the related question.

mbomb007

Posted 2017-06-29T10:24:54.330

Reputation: 21 944

works not for 8192 – Jörg Hülsermann – 2017-06-29T18:09:11.927

It doesn't work for that on the related question either, because of the recursion depth. I'm not sure what the consensus is on that. – mbomb007 – 2017-06-29T19:26:45.823

Some other answers have the same problem. I give only the info – Jörg Hülsermann – 2017-06-29T19:37:34.760

0

Retina, 70 bytes

.+
$*
1+
$&;$&;
{`^(1+);(?=(\b1|1\2)+;)\1(1*);1*
$3
}`;(1*)$
1$1;1$1
1

Try it online! Link includes test suite. Explanation: The algorithm works with three numbers, the input number, the sum of the input number and the current triangular number, and the index of the current triangular number. If the sum is triangular (using @MartinEnder's excellent algorithm) then the whole thing is replaced by the difference of the sum and the original number, thus achieving the desired result. Otherwise, the index is incremented and added to the sum, until the sum becomes triangular. Note that if the input number is zero then all of this is simply ignored as the result is zero anyway.

Neil

Posted 2017-06-29T10:24:54.330

Reputation: 95 035

0

Swift 3.0,97 bytes

let n=4
var o=0,s=0.0;for i in 0...n{o=i*(i+1)/2;s=sqrt(Double(8*(n+o)+1))
if floor(s)==s{break}}

To see output use print(o)

Try it online!

A. Pooja

Posted 2017-06-29T10:24:54.330

Reputation: 41

0

Ruby, 44 bytes

->n{*r=a=b=0;r<<a+=b+=1until r-[a-n]!=r;a-n}

Try it online!

G B

Posted 2017-06-29T10:24:54.330

Reputation: 11 099