# Counter-Fibonacci Sequences

Given three numbers m,n and p, your task is to print a list/array of length p starting with m and n and each element after p represents the difference of the 2 numbers before it, m-n (Counter-Fibonacci Sequence)

For this challenge you can either use a function to return or print the result or a full program.

### Input

Three integers, m,n and p, separated by newlines/spaces/commas, whatever your language supports, but you should specify your input format. Code insertion is disallowed.

### Output

The numbers contained by the Counter-Fibonacci Sequence, in any of the following formats (this example: m = 50, n = 40, p = 6):

• 50,40,10,30,-20,50 (or with spacing after commas)
• [50,40,10,30,-20,50] (or with spacing after commas)
• 50 40 10 30 -20 50 (or with \n(newlines) instead of spaces)
• {50,40,10,30,-20,50} (or with spaces instead of commas)

### Examples

Input => Output

50,40,10 => 50,40,10,30,-20,50,-70,120,-190,310
-100,-90,7 => -100,-90,-10,-80,70,-150,220
250,10,8 => 250,10,240,-230,470,-700,1170,-1870

### Rules

• You are guaranteed that p is higher than 1
• You should provide a way to test your program, if possible
• Take note that this loopholes are forbidden and code insertion is disallowed, as mentioned above

Your code must be as short as possible, since this is . No answer will be accepted, because this challenge is meant to find the shortest answer by language, avoiding an unfair advantage to golfing languages.

Related Question by ETHproductions: Monday Mini-Golf #1: Reverse Fibonacci Solver

• Related, possible duplicate. It's basically the same challenge as this one, but outputting in reverse order from a specific spot in the sequence. – ETHproductions Mar 16 '17 at 15:24
• @ETHproductions might be considered a dupe, but this is a bit different, trying to see the shortest solution in each language – Mr. Xcoder Mar 16 '17 at 15:27
• Yeah, there wasn't as much worry about language inequality back then ;-) I don't think it makes a big difference though. The main difference here is that you can pretty much leave out the first step of the algorithm you would have used to solve that challenge (working backwards to find the starting point) – ETHproductions Mar 16 '17 at 15:29
• @ETHproductions indeed there are small differences. If you wish this challenge to be removed, I'll totally do it. – Mr. Xcoder Mar 16 '17 at 15:30
• I personally think it's fine. Aside, are we allowed to have a trailing separator? – ETHproductions Mar 16 '17 at 15:37

a#b=a:b#(a-b)
(.(#)).(.).take

Length p is the first parameter. Usage example: ( (.(#)).(.).take ) 10 50 40 -> [50,40,10,30,-20,50,-70,120,-190,310]. Try it online!.

Shortening the list to p elements takes more bytes than producing it.

# Jelly, 6 bytes

_@Ð¡+Ṗ

Try it online!

### How it works

_@Ð¡+Ṗ  Main link. Left argument: m. Right argument: n. Third argument: p

+   Yield (m + n), the term that comes before m.
Ð¡    Execute the link to the left p times, starting with left argument m and
right argument (m + n). After each execution, replace the right argument
with the left one and the left argument with the previous return value.
Yield all intermediate values of the left argument, starting with m.
_@          Subtract the left argument from the right one.
This yields the first (p + 1) terms of the sequence, starting with m.
Ṗ   Pop; discard the last term.

# Python 2, 39 bytes

-2 bytes thanks to ETHproductions

-1 byte thanks to Dennis

f=lambda m,n,p:p*[0]and[m]+f(n,m-n,p-1)

Try it Online!

# JavaScript (ES6), 33 bytes

f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[]

Returns a string of the format 1,2,3, — without using strings!

### Test snippet

f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[]

console.log(f(50,40,10))
console.log(f(-100,-90,7))
console.log(f(250,10,8))

# Perl 6, 25 bytes

{($^m,$^n,*-*...*)[^$^p]} Try it ## Expanded: { # bare block lambda with placeholder parameters ｢$m｣ ｢$n｣ ｢$p｣
(
$^m,$^n,  # declare first two params, and use them

* - *      # WhateverCode lambda which subtracts two values

...        # keep using that to generate values

*          # never stop (instance of type Whatever)

)[ ^ $^p ] # declare last param, and use it to grab the wanted values # ｢^$^p｣ is short form of range op
# ｢0 ..^ $^p｣ which excludes the ｢$p｣
}

# CJam, 15 bytes

q~2-{1$1$-}*]S*

1 extra byte because CJam doesn't naturally use one of the allowed output formats >_<

Try it online!

Explanation

q~               e# Read and eval the input
2-             e# Subtract 2 from p (to account for m and n being in the list)
{            e# Run this block p-2 times:
1$1$-       e#   Copy the top values and subtract
}*     e# (end of block)
]    e# Wrap the stack in an array
S*  e# Join with spaces

# 05AB1E, 9 7 bytes

ÍFÂ2£¥«

Try it online!

Explanation

ÍF          # p-2 times do
Â         # create a reversed copy of the current list
2£       # take the first 2 elements of the list
¥      # calculate delta
«     # append to the list

# Röda, 38 bytes

f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_}

Try it online!

Explained:

f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_}
f i,a,b{                             } /* Function declaration */
seq 1,i                        /* Push numbers 1..i to the stream */
|{|_|               }_  /* For each number in the stream: */
[a];               /*   Push the current value of a */
b=a-b;         /*   Set b = the next number */
a=a-b    /*   Set a = the previous value of b */

(m!n)0=[]
(m!n)p=m:(n!(m-n))(p-1)

Call using (m!n)p. Works by defining ! as an infix function that takes in m and n and returns a function that takes p and returns the desired result.

• Nice! I didn't think of making the function infix, so my best try with haskell was 34. BTW you can replace the newline with ; to make it single-line, so it looks a little more codegolfy. – AlexJ136 Mar 16 '17 at 20:46

# Ruby, 31 bytes

->m,n,p{p.times{m,n=n,(p m)-n}}

The straightforward solution

# PHP, 76 Bytes

[,$a,$b,$c]=$argv;for($r=[$a,$b];$c---2;)$r[]=-end($r)+prev($r);print_r($r);

## PHP, 84 Bytes

[,$a,$b,$c]=$argv;for($r=[$a,$b];$c>$d=count($r);)$r[]=$r[$d-2]-end($r);print_r(\$r);

# Pyth, 18 bytes

JEKEVEJ=N-JK=JK=KN

Try it online!

Input and output are both delimited by newlines.

How it works:

JEKE                Read two lines of input to J and K
VE              Read another line and loop that many times:
J               Print J
=N-JK          Set N to J - K (Pyth uses prefix notation)
=JK       Set J to K
=KN    Set K to N

# Mathematica, 26 bytes

{-1,1}~LinearRecurrence~##

Lovin' the builtin. Takes input in the form {{m, n}, p}. LinearRecurrence wants the know the coefficients of the linear combination of previous elements to use to generate new elements, which in this case is {-1,1}.

## QBIC, 35 33 bytes

:::?'a;b;[c-2|e=a-b?e';┘a=b┘b=e

Saved 2 bytes by placing the first PRINT into one code literal.

Explanation (35 byte version):

:::         Get parameters a, b, c from the cmd-line
';       This suppresses a newline when printing
?a   b';   PRINT a and b
[c-2|       FOR x=1; x<=(c-2); x++
e=a-b       calculate the next term of the sequence
?e';       Print it, suppressing newline
┘a=b        ┘ denotes a syntactic linebreak; shove the numbers one over
┘b=e        dito
FOR-loop is auto-closed
• Have any idea of an online interpreter to test this? – Mr. Xcoder Mar 16 '17 at 17:54
• @Mr.Xcoder no online interpreter yet, sorry. I've added a link to the interpreter, which is a DOSBOX project running QBasic, running QBIC. – steenbergh Mar 16 '17 at 18:10
• The explanation is worth more than the interpreter @steenbergh, thanks for responding! – Mr. Xcoder Mar 16 '17 at 18:11

# C, 128 bytes

m,n,p,z;main(c,v)char**v;{m=atoi(v[1]);n=atoi(v[2]);p=atoi(v[3])-2;printf("%d,%d",m,n);while(p--)z=m,m=n,n=z-m,printf(",%d",n);}

This program parses the three arguments m, n and p from the command-line, and prints the output as specified.

Modern C compilers allow you to omit basic imports, and thus we can use printf and atoi without the #includes.

Global variables are int by default when declared without a type - this saves a lot of space.

# Java, 66 bytes

For once, lambdas are the inefficient approach to golfing due to the very roundabout way of applying recursion to them that requires a lot of extra bytes.

Golfed:

String f(int m,int n,int p){return""+m+(p>1?","+f(n,m-n,p-1):"");}

Ungolfed:

public class CounterFibonacciSequences {

private static final int[][] INPUTS = new int[][] { //
{ 50, 40, 10 }, //
{ -100, -90, 7 }, //
{ 250, 10, 8 } };

private static final String[] OUTPUTS = new String[] { //
"50,40,10,30,-20,50,-70,120,-190,310", //
"-100,-90,-10,-80,70,-150,220", //
"250,10,240,-230,470,-700,1170,-1870" };

public static void main(String[] args) {
for (int i = 0; i < INPUTS.length; ++i) {
final int m = INPUTS[i][0];
final int n = INPUTS[i][1];
final int p = INPUTS[i][2];
System.out.println("M: " + m);
System.out.println("N: " + n);
System.out.println("P: " + p);
System.out.println("Expected: " + OUTPUTS[i]);
System.out.println("Actual:   " + new CounterFibonacciSequences().f(m, n, p));
System.out.println();
}
}

String f(int m, int n, int p) {
return "" + m + (p > 1 ? "," + f(n, m - n, p - 1) : "");
}
}

# AHK, 68 bytes

m=%1%
n=%2%
3-=2
Send %m%n%n%n
Loop,%3%
{
n:=m-n
m-=n
Send %n%n
}

Getting' really tired of not knowing how / being able to use passed arguments (%1%, %2%, ...) directly in any math functions

# Python 2, 93 90 bytes

u,t=int,input;m,n,p=u(t()),u(t()),u(t());l=[m,n]
for i in range(p-2):l.append(l[-2]-l[-1])

Try it online!

Saved 3 bytes thanks to @Mr.Xcoder

It works by taking the numbers as input and formatting them correctly, then using a for loop to generate a list based on the inputted numbers.

• You can remove the space after comma in that range to save 1 byte – Mr. Xcoder Mar 18 '17 at 6:04
• And it may be shorter if you map your input with ints and input.split – Mr. Xcoder Mar 18 '17 at 6:05
• @Mr.Xcoder I tried the split, but it ended up being longer. – Comrade SparklePony Mar 18 '17 at 14:39
• Ok, I couldn't test it. It's good anyway. – Mr. Xcoder Mar 18 '17 at 14:40
• And the range does not need the first argument – Mr. Xcoder Mar 18 '17 at 14:48

# Swift - 85 bytes

func y(x:Int,y:Int,z:Int){var m=x,n=y,p=z,c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}}

Usage: y(x:50,y:40,x:6)

# Swift - 84 bytes

func z(l:[Int]){var m=l[0],n=l[1],p=l[2],c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}}

Usage: z(l: [50,40,6])

Output:

50
40
10
30
-20
50

# Python - 55 bytes

def s(m,n,p):
for i in range(p):print(m);c=m;m=n;n=c-n

Try it online! & Usage: s(50,40,6)

Note: Solution without lambda