# 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.

var QUESTION_ID=113051,OVERRIDE_USER=59487;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

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