# The plus-minus sequence

The plus-minus sequence is one that starts with two seeds, a(0) and b(0). Each iteration of this sequence is the addition and subtraction of the previous two members of the sequence. That is, a(N) = a(N-1) + b(N-1) and b(N) = a(N-1) - b(N-1).

Objective Produce the plus-minus sequence, in infinitude or the first K steps given K. You may do this using an infinite output program, a generator, or a function/program that gives the first K steps. The output order does not matter, so long as it is consistent. (I.e., b(K) a(K) or a(K) b(K), with some non-numeric, non-newline separator in between.) The output must start with the input.

## Test cases

For inputs 10 2 (of a(0) b(0), this is a possible output for the first K approach (or a subsection of the infinite approach):

10     2
12     8
20     4
24     16
40     8
48     32
80     16
96     64
160    32
192    128
320    64
384    256
640    128
768    512
1280   256
1536   1024
2560   512
3072   2048
5120   1024
6144   4096
10240  2048
12288  8192
20480  4096
24576  16384
40960  8192
49152  32768
81920  16384
98304  65536


For inputs 2 20 10 (a(0) b(0) k):

2     20
22   -18
4     40
44   -36
8     80
88   -72
16    160
176  -144
32    320
352  -288


This is a , so the shortest program in bytes wins.

• I notice a(2n) = a(0)·2ⁿ and b(2n) = n(0)·2ⁿ, but that's probably not useful here. – Neil Apr 3 '16 at 21:18
• Can the non-numeric separator between a and b be a newline? – Suever Apr 3 '16 at 22:32
• @Suever No, it cannot. – Conor O'Brien Apr 3 '16 at 22:33
• @CᴏɴᴏʀO'Bʀɪᴇɴ Thanks for the clarification! – Suever Apr 3 '16 at 22:34
• Returning a sequence is fine @guifa – Conor O'Brien Jun 28 '19 at 14:24

# Jelly, 5 bytes

ṄI;Sß


This is a recursive approach. Due to tail call optimization, the only limit is the ability to fit both integers into memory. Output is one list per line.

Try it online!

### How it works

ṄI;Sß  Main link. Argument: [b[n], a[n]] (n = 0 for original input)

Ṅ      Print [b[n], a[n]] to STDOUT.
I     Compute the increments of the list, i.e., [a[n] - [b[n]].
S   Compute the sum of the list, i.e., b[n] + a[n].
;    Concatenate the results to the left and to the right.
ß  Recursively call the main link.

• Wow. That is quite impressive. – Conor O'Brien Apr 3 '16 at 22:23
• What does Main link actually mean? – cat Apr 3 '16 at 22:26
• @cat It's like C's main function. Every line defines a different function/link, but the last one gets called automatically when the program is executed. – Dennis Apr 3 '16 at 22:27
• >Jelly programs consist of up to 257 different Unicode characters. Isn't there 256 bits in a byte? – thepiercingarrow Apr 4 '16 at 1:44
• @MarkWright ¶ and linefeeds can be used interchangeably. You can use both in UTF-8 mode, but there's only \x7f to represent them in Jelly's code page. – Dennis Apr 4 '16 at 1:48

## Python 2, 31 bytes

def f(a,b):print a,b;f(a+b,a-b)


Prints forever. Well, eventually you exceed the recursion limit, but that's a system limitation.

• How long do you think this can go on for before a recursion error is raised? – R. Kap Apr 4 '16 at 0:17
• @R.Kap it is ~1000. You can set this limit to whatever you want via sys.setrecursionlimit – Mathias711 Apr 4 '16 at 6:22
• @R.Kap It takes about 10 seconds on my machine. – xnor Apr 4 '16 at 6:58
• 10 seconds before raising a recursion error? Wow. In Python 3, I let mine go on for 30 minutes straight, and no error was raised whatsoever. I was able to print over 2000 digits for one of the numbers! I guess a while loop behaves differently than what you're doing. – R. Kap Apr 4 '16 at 7:00
• I tried using this with a lambda but it took more bytes (f=lambda a,b:print(a,b)or f(a+b,a-b)) – MilkyWay90 Jun 29 '19 at 17:58

# MATL, 10 bytes

tDtswPdhT


This version will output an infinite number of elements in the plus-minus sequence.

Try it Online! (stop it after running due to infinite loop)

Explanation

    % Implicitly grab input as a two-element array [a,b]
% do...while loop
tD  % Duplicate and display the top of the stack
ts  % Duplicate [a,b] and add them together
w   % Swap the top two elements on the stack
P   % Swap the order of b and a in preparation for diff
d   % Compute the difference between b and a
h   % Horizontally concatenate [a+b, a-b]
T   % Explicit TRUE to make it an infinite loop
% Implicit end of the do...while loop

• Does this automatically convert all very large numbers into scientific notation? – R. Kap Apr 4 '16 at 0:19
• @R.Kap It looks like it does. That doesn't appear to be explicitly forbidden in the original problem statement. – Suever Apr 4 '16 at 0:25
• Wow, that's pretty cool. In Python, if you have very big numbers, it still prints out all the digits, one at a time, so it gets a bit tedious looking at all that. I just thought that most other languages did that too, but it looks like Python is the unique one in this case. – R. Kap Apr 4 '16 at 0:29
• Well so in MATLAB (which MATL uses under the hood), you can change the output format to be whatever you want. The default of MATL is to display up to 15 numbers before switching to scientific notation. – Suever Apr 4 '16 at 0:33
• OOPS my bad, sorry, deleted ;) – thepiercingarrow Apr 4 '16 at 1:44

a#b=a:b:(a+b)#(a-b)


Produces an infinite sequence of numbers. Usage example:

Prelude> take 20 $2#20 [2,20,22,-18,4,40,44,-36,8,80,88,-72,16,160,176,-144,32,320,352,-288]  # Pyth, 10 9 bytes Thanks to @isaacg for 1 byte. #=Q,s Q-F  Prints an infinite sequence of pairs. $ pyth plusminus.p <<< "[10,2]" | head -n 15
[10, 2]
[12, 8]
[20, 4]
[24, 16]
[40, 8]
[48, 32]
[80, 16]
[96, 64]
[160, 32]
[192, 128]
[320, 64]
[384, 256]
[640, 128]
[768, 512]
[1280, 256]

• The first and last Qs can be removed - Pyth will fill them in implicitly. – isaacg Apr 4 '16 at 3:44
• @isaacg So that got implemented then? Cool. I tried removing the first one, but that didn't work. – PurkkaKoodari Apr 4 '16 at 12:27
• That's strange, removing the first one worked on my machine. – isaacg Apr 4 '16 at 12:29

# C, 81 bytes

a,b;main(c){for(scanf("%d%d%d",&a,&b,&c);c--;a+=b,b=a-b-b)printf("%d %d\n",a,b);}


# 05AB1E, 7 bytes

Uses the first-k method. Input in the following for:

k
[a, b]


Code:

FD=OsÆ‚


Explanation:

F        # For N in range(0, k).
D=      # Duplicate top of the stack and print without popping.
O     # Sum up the array.
sÆ   # Swap and perform a reduced subtraction.
‚  # Pair the top two elements. a, b --> [a, b]


Uses the CP-1252 encoding. Try it online!

• The code is vaguely reminiscent of the language name... – Conor O'Brien Apr 4 '16 at 13:52
• @CᴏɴᴏʀO'Bʀɪᴇɴ Hahaha, both unreadable – Adnan Apr 4 '16 at 13:56

# k, 12

{(+;-).\:x}\


.

k){(+;-).\:x}\[10;10 2]
10  2
12  8
20  4
24  16
40  8
48  32
80  16
96  64
160 32
192 128
320 64


Could also be called in the form of

k)10{(+;-).\:x}\10 2


## APL, 37 chars

{⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z}


Can be used as

    {⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z} 10 2
10 2
12 8
20 4
24 16
40 8
48 32
80 16
[...]


or

      {⍺←3⊃3↑⍵⋄⎕←z←2↑⍵⋄⍺=1:⋄(⍺-1)∇(+/,-/)z} 10 2 6
10 2
12 8
20 4
24 16
40 8
48 32


# MathGolf, 8 bytes

ôαp‼+-∟


Try it online!

Takes input in reverse order, but that's simply because that's how they are pushed onto the stack. Otherwise it'd be 1 byte longer. 2-3 bytes comes from the output. Without the need of actually printing one pair per line, the program could be æ‼+-∟ (fills the stack with the elements of the sequence indefinitely), or É‼+-∟ (prints all elements of the sequence except the first one to debug, as long as -d flag is active).

## Explanation

ô      ∟   do-while-true
         duplicate the top two items
αp       wrap last two elements in array and print
‼      apply next two operators to the top stack elements
+     pop a, b : push(a+b)
-    pop a, b : push(a-b)

• Hi Max. Not sure since when, but currently the MathGolf version on TIO doesn't accept string input at all anymore.. Doesn't matter what builtin I use, even without any code for the program at all, if a string input is given like for example ABC, I get an error on line stdin = StdIn(line) in the Python code.. – Kevin Cruijssen Jul 1 '19 at 7:26
• @KevinCruijssen Hi! String input should be given as 'ABC' or "ABC". Internally, ast.literal_eval is used to parse the input. There are still some quirks that need to be ironed out, but you should be able to do this. – maxb Jul 1 '19 at 7:31
• Ah ok, that makes sense. Btw, is there a builtin to split a string/number into parts of certain size or some amount of equal-sized parts? I.e. ABCDEF to [AB, CD, EF]? – Kevin Cruijssen Jul 1 '19 at 7:34
• Nvm, apparently there isn't, but I've been able to find a way to do so: 2ô_2<\1>] (hard-coded to input-length 6 and split into parts of size 2, since that was what I needed, but should probably be modifiable to work for generic input-sizes and part-sizes). – Kevin Cruijssen Jul 1 '19 at 10:05
• Perhaps you have overlooked the behavior of the division operator for strings? / does exactly what you say, split into chunks of $n$ characters. Check it out – maxb Jul 1 '19 at 11:46

# Python 3.5, 55 43 bytes:

def q(a,b):
while 1:print(a,b);a,b=a+b,a-b


Prints out the correct sequence seemingly forever. I have been able to let this go on for about 30 minutes without any error being raised, and the program had printed out 2301 digits for the first number, and 1150 digits for the second! Based on this, I guessing that, being provided sufficient hardware to run on, this can go on for WAY longer and print out WAY more digits, and also has theoretically no recursion limit, courtesy of the while loop!

• I think you're supposed to print out the current values at the beginning of the loop, so that the first output is the same as the input. Also, as this is code golf, you should optimise away the parentheses and intermediate variables. Finally, as a style nit, I think you should consider naming the variables a and b to match the question. – Neil Apr 4 '16 at 8:45
• @Neil Thanks for the tips. :) – R. Kap Apr 4 '16 at 8:56
• I'm confused; you've got both a while and a recursive call now... – Neil Apr 4 '16 at 8:58
• @Neil Yeah, I did not notice that. Now it's fixed, and just a while loop, with theoretically no limits whatsoever. – R. Kap Apr 4 '16 at 9:06

# Reng v.3.2, 9 bytes (self-answer, non-competing)

ii¤ææö±2.


Takes two inputs (a b) and outputs b a. Try it here!

i takes input twice, ¤ duplicates the stack, æ prints a number and a space (and does so twice, there being two), ö prints a newline, ± does what you might expect, and 2. skips the next two characters, wrapping around the input getting characters.

• Hmm, would you mind explaining what each of those hieroglyphics do to a newb like me? :) – Kevin Cruijssen Apr 4 '16 at 9:06
• @KevinCruijssen I have explained the mystery. :) – Conor O'Brien Apr 4 '16 at 11:20

## Python 2.7, 56, 42 bytes:

a,b=input()
while 1:print a,b;a,b=a+b,a-b


Simple loop that either prints forever(ish).

• You can use a single space for the indent level to save bytes. Also, you do not have to do both methods, just one or the other, so you can remove the default parameter. – Conor O'Brien Apr 4 '16 at 0:58
• Oh damn didn't notice notepad was making my tab into 4 spaces, and sure thing i'll restrict it to one, Thanks. – Serdalis Apr 4 '16 at 1:00
• If you make this a program by changing the first line to a,b=input(), you can remove the indent. – xnor Apr 4 '16 at 6:29
• @xnor Thanks, only saves 1 byte but it's not ugly anymore! – Serdalis Apr 4 '16 at 7:40

## Batch, 54 bytes

@echo %1 %2
@set/aa=%1+%2
@set/ab=%1-%2
@%0 %a% %b%


Note that CMD.EXE is limited to 32-bit signed integers, so it will quickly overflow and print garbage and error messages.

• Always love to see a batch answer around here! :D – Conor O'Brien Apr 3 '16 at 21:24
• @CᴏɴᴏʀO'Bʀɪᴇɴ I wrote it especially for you. – Neil Apr 3 '16 at 21:43

# Julia, 25 bytes

a<|b=[a b]|>show<a+b<|a-b


Maximum syntax abuse. Julia is weird. Try it online!

### Alternate version, 29 bytes

Note that the output will eventually overflow unless you call <| on a BigInt. Unfortunately, show will prefix each array with BigInt in this case. At the cost of four more bytes, we can generated whitespace-separated output for all numeric types.

a<|b="$a$b
"|>print<a+b<|a-b


Try it online!

### How it works

We define the binary operator <| for out purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser. While \ (not explicitly defined for integers) is one byte shorter, its high precedence would require replacing a+b<|a-b with (a+b)\(a-b) (+3 bytes) or \(a+b,a-b) (+2 bytes).

When a<|b is executed, it starts by calling show to print [a b] to STDOUT. Then, a+b<|a-b recursively calls <| on the sum or the difference.

Since the recursion is (supposed to be) infinite, the comparison < is never performed; it sole purpose is chaining the two parts of the code. This saves two bytes over the more straightforward alternative ([a b]|>show;a+b<|a-b).

# Perl 6, 23 bytes (infinite)

Edit: thanks to JoKing, the sequence version is now the shortest (also removed .say per clarification from OP:

b=$2 for i in seq$3;{ echo -e "$a\t$b";c=$a;a=$((c+b));b=$((c-b));}  Invocation: ./codegolf.sh 2 10 5  # CP/M 8080, 47 bytes z80 mnemonics but nothing the 8080 doesn't have, source commented once I decided to count the output rather than the input but terse function names retained, hand assembled so forgive the 'xx's where I know the number of bytes but haven't worked out the output addresses or offsets: # setup ld c, 2 0e 02 # loop .s # update H (temporarily in B) ld a, h 7c add l 85 daa 27 ld b, a 46 # update L ld a, h 7c sub l 95 daa 27 ld l, a 6f # copy B back to H, output H ld h, b 60 call +o cd xx xx # output L ld b, l 45 call +o cd xx xx # repeat jr -s 18 xx # output a two-digit BCD value followed by a space .o # output high digit ld a, b 78 rra 1f rra 1f rra 1f rra 1f call +ob cd xx xx # output low digit ld a, b 78 call +ob cd xx xx # output a space ld e, #$20  1e 20
call 5      cd 00 05

# return
ret         c9

# output a single BCD digit
.ob
and #$f e6 0f add #$30    c6 30
ld e, a     5f
call 5      cd 00 05
ret         c9


# Clojure, 44 bytes

#(iterate(fn[[a b]][(+ a b)(- a b)])[%1 %2])


Function that produces an infinite lazy sequence.

# Perl 5, 40 bytes

requires -E (free)

sub a{say"@_";($c,$d)=@_;a($c+$d,$c-$d)}


or (same length)

$_=<>;{say;/ /;$_=$+$'.$".($-$');redo}  (I struck through the latter because it should have rounding errors for some iterations.) Hat-tip. But I suspect there must be a shorter Perl 5 solution. • If there is a shorter solution, Ton Hospel will find it. :P – Conor O'Brien Apr 4 '16 at 18:11 • Took a while, but I found a shorter way: – Xcali Jun 27 '19 at 2:46 # RETURN, 21 bytes [¤.' ,$.'
,¤¤+2ª-F]=F


Try it here.

Recursive operator-lambda. Usage:

[¤.' ,$.' ,¤¤+2ª-F]=F10 2F  # Explanation [ ]=F declare function F for recursion ¤.' ,$.'␊,            output top 2 stack items along with trailing newline
¤¤+2ª-      get plus and minus of top 2 stack items
F     recurse!


# ><>, 26 bytes

:?!;1-r:n48*o:@@:nao:@+}-$ Call with a, b, n on the stack, where n is the number of turns or a negative value for infinite output. Outputs a and b separated by a space. As an explanation, here is how the stack evolves during runtime : abn nba nbaa naab naabb nabab nab+ +nab +n- +-n  You can try it on the online interpreter with a positive amount of turns but you will need to use the official python interpreter to test the infinite mode. $ python fish.py -c ':?!;1-r:n48*o:@@:nao:@+}-\$' -t 0.01 -v 10 2 -1
10 2
12 8
20 4
24 16
40 8
48 32
80 16
96 64
160 32
192 128
320 64
384 256
640 128
768 512
1280 256
1536 1024
2560 512
3072 2048
5120 1024
6144 4096
10240 2048
12288 8192
20480 4096
24576 16384
40960 8192
49152 32768
81920 16384
98304 65536
163840 32768
196608 131072
327680 65536
393216 262144
655360 131072
786432 524288
1310720 262144
[...]


# Fuzzy Octo Guacamole, 17 16 bytes

(non-competing, uses features later than the challenge)

^^(:C.Zs.aZ.s.-)


This was hard to make, due to client-side errors. But I got it!

Walkthrough:

^^                # Get input twice, pushes it to the stack.
(               # Start a infinite loop.
:              # Prints the stack, and since it has [a,b] is just the output.
C             # Copy the active stack to the inactive stack.
.            # Shift the active stack.
Z           # Reverse the stack.
s          # Move the top item on the active stack to the top of the inactive.
.         # Switch stacks again.
a        # Add the top 2 items, giving the first new item.
Z       # Reverse the stack, so we keep the 'a' safe and prepare for the 'b'.
.      # Switch stacks.
s     # Move the top item on the active stack to the top of the inactive stack.
.    # Switch stacks.
-   # Minus the top 2 items, giving 'b'.
)  # End infinite loop.

• I don't know FOG all that well, but can't you move the : to the beginning of the loop and eliminate the need for printing twice? – Conor O'Brien Apr 5 '16 at 15:29
• oooooh @CᴏɴᴏʀO'Bʀɪᴇɴ thanks. – Rɪᴋᴇʀ Apr 5 '16 at 16:06
• Don't forget to update the explanation ;) – Conor O'Brien Apr 5 '16 at 16:45
• @CᴏɴᴏʀO'Bʀɪᴇɴ whadda ya mean? :P – Rɪᴋᴇʀ Apr 5 '16 at 18:41

## Seriously, 12 bytes

,,1WX■@│+)-1


Outputs an infinite stream, format is b(n) a(n), one pair of outputs per line.

No online link because TryItOnline doesn't do so well with infinite loops.

Explanation:

,,1WX■@│+)-1
,,1           push a(0), push b(0), push 1
W          while loop:
X           discard the 1 (only used to make sure the while loop always runs)
■          print all stack elements, separated by spaces, without popping
@│        swap, duplicate entire stack
+)      push a(n) + b(n) (a(n+1)) and move it to the bottom of the stack
-     push a(n) - b(n) (b(n+1))
1    push 1 to make sure the loop continues


# J, 16 12 bytes

0&(]+/,-/)~<


Produces only the first k values for the sequence based on the given seeds.

Saved 4 bytes using the trick (or syntactic sugar) shown by @randomra in this comment.

## Usage

   f =: 0&(]+/,-/)~<
2 20 f 10
2   20
22  _18
4   40
44  _36
8   80
88  _72
16  160
176 _144
32  320
352 _288


# C#, 50 bytes

f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);};


Full source, including test case:

using System;
using System.Numerics;

namespace PlusMinusSequence
{
class Program
{
static void Main(string[] args)
{
Action<BigInteger,BigInteger>f=null;
f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);};
BigInteger x=10, y=2;
f(x,y);
}
}
}


The BigInteger data type is used so the numbers don't overflow and become 0. However, since it is a recursive solution, expect a stack overflow.