Golf a Custom Fibonacci Sequence

26

1

The Fibonacci sequence is a fairly well known thing around here. Heck, it even has its own tag. However, for all that, we sure like to stick to our roots of 1, 1, ... (or is it 0, 1, ...? We may never know...). In this challenge, the rules are the same, but instead of getting the nth item in the Fibonacci sequence, you will get the nth item in the Fibonacci-esque sequence starting with x, y, ....

Input

Three integers, in whatever order you want. n is the index (0 or 1 indexed) of term in the sequence for your output. x and y are the first two items in your current program run's Fibonacci sequence.

Output

The nth term in the Fibonacci sequence starting with x, y.

Test Cases

(0-indexed)

n   x     y     out
5   0     0     0
6   0     1     8
6   1     1     13
2   5     5     10
10  2     2     178
3   3     10    23
13  2308  4261  1325165
0   0     1     0
1   0     1     1

(1-indexed)

n   x     y     out
6   0     0     0
7   0     1     8
7   1     1     13
3   5     5     10
11  2     2     178
4   3     10    23
14  2308  4261  1325165
1   0     1     0
2   0     1     1

Caveats

Assume 0 <= x <= y.

Please note your input order (must be constant).

Stephen

Posted 2017-05-17T13:45:49.483

Reputation: 12 293

Can we take a list as input? – Business Cat – 2017-05-17T14:41:12.567

@BusinessCat you mean like [1, 2, 3]? Yes. Whatever you need to accept 3 integers. – Stephen – 2017-05-17T14:42:05.027

@StephenS How about taking an input as n,[x,y] where n is a number and x and y are numbers in a list? That's probably being a little too flexible though ;) – Tom – 2017-05-17T14:54:16.620

@Tom as long as all you are doing is accepting 3 integers, I don't care how you format your input (so yes, that would be acceptable. You only can't use anything in the input besides the 3 integers as information). – Stephen – 2017-05-17T14:58:09.597

Related (Numberphile), Related (OEIS) (I was hoping the Brady Numbers would be a test case...) – CAD97 – 2017-05-17T17:41:50.950

1@CAD97 I'll add them, I had forgotten about them :) – Stephen – 2017-05-17T17:48:10.650

I honestly don't understand why this isn't being considered as a dupe. In most languages, surely, it's simply going to be a case of replacing the 2 initial values of x & y with input values? I've seen the dupe hammer swung on questions that differ a lot more than these two. – Shaggy – 2017-05-17T22:04:24.197

@Shaggy it was dupe hammered (not 5 votes) then undupe hammered (not 5 votes). Dunno who unduped it. – Stephen – 2017-05-17T22:15:20.403

1Related – xnor – 2017-05-17T22:55:16.710

There are currently no testcases for n=1 (or 0 if indexed as such), do we need to be able to handle this? – JAD – 2017-05-18T07:11:49.333

@JarkoDubbeldam yes, editing in, thank you – Stephen – 2017-05-18T16:00:23.140

Quite related. The only difference in that challenge is that you have to first work backwards until you find the "first item" in the custom sequence. – ETHproductions – 2017-07-07T17:32:39.023

Can I -1-index? Return y for n == 0, x+y for n == 1, and so on? – Khuldraeseth na'Barya – 2018-04-21T23:34:20.337

@Scrooble As long as you return x for n = -1 – Stephen – 2018-04-21T23:48:21.290

Answers

16

Jelly, 3 bytes

+¡ạ

Takes x, y, and n (0-indexed) as separate command-line arguments, in that order.

Try it online!

How it works

+¡ạ  Main link. Left argument: x. Right argument: y. Third argument: n

  ạ  Yield abs(x - y) = y - x, the (-1)-th value of the Lucas sequence.
+¡   Add the quicklink's left and right argument (initially x and y-x), replacing
     the right argument with the left one and the left argument with the result.
     Do this n times and return the final value of the left argument.

Dennis

Posted 2017-05-17T13:45:49.483

Reputation: 196 637

11

CJam, 14 9 bytes

l~{_@+}*;

Try it online!

Input format is "x y n". I'm still a noob at this, so I'm 100% sure there are better ways to do this, but please instead of telling me "do this" try to only give me hints so that I can find the answer myself and get better. Thanks!

FrodCube

Posted 2017-05-17T13:45:49.483

Reputation: 539

1ririri can be shortened to 2 bytes. fI can be shortened to 1 byte. – Dennis – 2017-05-17T14:54:44.713

6Welcome to PPCG! – Martin Ender – 2017-05-17T14:54:54.983

@Dennis improved! Thank you! And thanks for the welcome. – FrodCube – 2017-05-17T15:04:45.377

9

JavaScript (ES6), 27 26 bytes

Nothing fancy here, just a standard JS Fibonacci function with the initial values of 0 & 1 removed.

n=>g=(x,y)=>n--?g(y,x+y):x

Try it

f=
n=>g=(x,y)=>n--?g(y,x+y):x
o.value=f(i.value=13)(j.value=2308,k.value=4261)
oninput=_=>o.value=f(+i.value)(+j.value,+k.value)
*{font-family:sans-serif;}
input{margin:0 5px 0 0;width:50px;}
#o{width:75px;}
<label for=i>n: </label><input id=i type=number><label for=j>x: </label><input id=j type=number><label for=k>y: </label><input id=k type=number><label for=o>= </label><input id=o>

Shaggy

Posted 2017-05-17T13:45:49.483

Reputation: 24 623

9

Python 2, 37 bytes

f=lambda x,y,n:n and f(y,x+y,n-1)or x

Try it online!

0-indexed, you may need to adjust the recursion limit for n≥999

ovs

Posted 2017-05-17T13:45:49.483

Reputation: 21 408

6

Python 2, 40 bytes

0-indexed
Try it online

n,a,b=input()
exec'a,b=b,a+b;'*n
print a

Dead Possum

Posted 2017-05-17T13:45:49.483

Reputation: 3 256

Haha not subject to a recursion/stack limit unlike some other answers. Nice trick. – ShreevatsaR – 2017-05-19T04:16:32.087

@ShreevatsaR Thanks! But recursive lambda beats me anyway :D – Dead Possum – 2017-05-19T08:17:58.257

5

Haskell, 30 bytes

x#y=(f!!)where f=x:scanl(+)y f

Try it online! 0-indexed. Use as (x#y)n, e.g. (0#1)5 for the fifth element of the original sequence.

The most likely shortest way to get the Fibonacci sequence in Haskell is f=0:scanl(+)1f, which defines an infinite list f=[0,1,1,2,3,5,8,...] containing the sequence. Replacing 0 and 1 with arguments x and y yields the custom sequence. (f!!) is then a function returning the nth element of f.

Laikoni

Posted 2017-05-17T13:45:49.483

Reputation: 23 676

5

Mathematica, 36 bytes

LinearRecurrence[{1,1},{##2},{#+1}]&

input

[n,x,y]

J42161217

Posted 2017-05-17T13:45:49.483

Reputation: 15 931

1You can use ##2 instead of #2,#3. – alephalpha – 2017-05-18T08:45:12.503

very nice! fixed! – J42161217 – 2017-05-18T08:58:09.850

5

PowerShell, 40 bytes

$n,$x,$y=$args;2..$n|%{$y=$x+($x=$y)};$y

Try it online!

Nik Weiss

Posted 2017-05-17T13:45:49.483

Reputation: 91

4

Brain-Flak, 38 bytes

{({}[()]<(({}<>)<>{}<(<>{}<>)>)>)}{}{}

Try it online!

{({}[()]<                      >)}     # For n .. 0
         (({}<>)<>            )        # Copy TOS to the other stack and add it to...
                  {}                   # The second value
                    <(<>{}<>)>         # Copy what was TOS back
                                  {}{} # Pop the counter and the n+1th result

Riley

Posted 2017-05-17T13:45:49.483

Reputation: 11 345

4

Ruby, 27 bytes

->a,b,n{n.times{b=a+a=b};a}

G B

Posted 2017-05-17T13:45:49.483

Reputation: 11 099

3

TAESGL, 4 bytes

ēB)Ė

1-indexed

Interpreter

Explanation

Input taken as n,[x,y]

 ēB)Ė
AēB)     get implicit input "A" Fibonacci numbers where "B" is [x,y]
    Ė    pop the last item in the array

Tom

Posted 2017-05-17T13:45:49.483

Reputation: 3 078

3

Jelly, 6 bytes

;SḊµ¡I

Try it online!

Explanation

   µ¡  - repeat n times (computes the n+1th and n+2th element):
 S     -  take the sum of the elements of the previous iteration (starting at (x,y))
;      -  append to the end of the previous iteration
  Ḋ    -  remove the first element
     I - Take the difference of the n+1th and n+2th to get the n-th.

fireflame241

Posted 2017-05-17T13:45:49.483

Reputation: 7 021

3

Prolog (SWI), 77 bytes

f(N,Y,Z):-M is N-1,f(M,X,Y),Z is X+Y.
l(N,A,B,X):-asserta(f(0,A,B)),f(N,X,_).

Try it online!

Started off golfing Leaky Nun's answer and arrived at something completely different.

This one has a rule for (Nᵗʰ, (N+1)ᵗʰ) in terms of ((N-1)ᵗʰ, Nᵗʰ) and uses database management to assert 0ᵗʰ and 1ˢᵗ elements at runtime.

f(N,X,Y) means Nᵗʰ element is X and (N+1)ᵗʰ element is Y.

eush77

Posted 2017-05-17T13:45:49.483

Reputation: 1 280

3

Octave, 24 bytes

@(n,x)(x*[0,1;1,1]^n)(1)

Input format: n,[x,y].

Try it online!

alephalpha

Posted 2017-05-17T13:45:49.483

Reputation: 23 988

2

Braingolf, 15 bytes

VR<2-M[R!+v]R_;

_; is no longer needed on the latest version of Braingolf, however that's as of ~5 minutes ago, so would be non-competing.

Skidsdev

Posted 2017-05-17T13:45:49.483

Reputation: 9 656

2

Python 2, 112 bytes

1-indexed.

import itertools
def f(x,y):
 while 1:yield x;x,y=y,x+y
def g(x,y,n):return next(itertools.islice(f(x,y),n-1,n))

Try it online!

totallyhuman

Posted 2017-05-17T13:45:49.483

Reputation: 15 378

Erp, too late and too big. – totallyhuman – 2017-05-17T14:12:26.593

2

Prolog (SWI), 85 bytes

l(0,X,Y,X).
l(1,X,Y,Y).
l(N,X,Y,C):-M is N-1,P is N-2,l(M,X,Y,A),l(P,X,Y,B),C is A+B.

Try it online!

0-indexed.

Leaky Nun

Posted 2017-05-17T13:45:49.483

Reputation: 45 011

Could you edit this answer? I seem to have accidentally downvoted it the day you posted it. – Esolanging Fruit – 2018-04-21T22:29:44.847

@EsolangingFruit done – Leaky Nun – 2018-04-21T22:30:26.923

2

PHP>=7.1, 55 Bytes

for([,$n,$x,$y]=$argv;$n--;$x=$y,$y=$t)$t=$x+$y;echo$x;

Online Version

PHP>=7.1, 73 Bytes

for([,$n,$x,$y]=$argv,$r=[$x,$y];$i<$n;)$r[]=$r[+$i]+$r[++$i];echo$r[$n];

Online Version

Jörg Hülsermann

Posted 2017-05-17T13:45:49.483

Reputation: 13 026

1Taking advantage of strange PHP's evaluation order: $y=+$x+$x=$y. Also, you can use just $n-- instead of $i++<$n. – user63956 – 2017-05-19T11:56:54.237

2

MATL, 7 bytes

:"wy+]x

Output is 0-based.

Try it at MATL Online!

Explanation

Let the inputs be denoted n (index), a, b (initial terms).

:"     % Implicitly input n. Do this n times
       %   At this point in each iteration, the stack contains the two most
       %   recently computed terms of the sequence, say s, t. In the first
       %   iteration the stack is empty, but a, b will be implicitly input
       %   by the next statement
  w    %   Swap. The stack contains t, s
  y    %   Duplicate from below. The stack contains t, s, t
  +    %   Add. The stack contains t, s+t. These are now the new two most
       %   recently comnputed terms
]      % End
x      % Delete (we have computed one term too many). Implicitly display

Luis Mendo

Posted 2017-05-17T13:45:49.483

Reputation: 87 464

2

R, 39 bytes

f=function(x,y,n)'if'(n,f(y,x+y,n-1),x)

A simple recursive function. Funnily enough this is shorter than anything I can come up with for the regular Fibonacci sequence (without built-ins), because this doesn't have to assign 1 to both x and y =P

Calculates n+1 numbers of the sequence, including the initial values. Each recursion is calculates with n-1 and stopped when n==0. The lowest of the two numbers is then returned, giving back the n-th value.

JAD

Posted 2017-05-17T13:45:49.483

Reputation: 2 898

2

dc, 36 bytes

?sdsbsa[lddlb+sdsbla1-dsa1<c]dscxldp

Try it online!

0-indexed. Input must be in the format n x y.

R. Kap

Posted 2017-05-17T13:45:49.483

Reputation: 4 730

2

Common Lisp, 49 Bytes, 0-indexed

(defun fib(n x y)(if(= 0 n)x(fib(1- n)y(+ x y))))

I'm a Lisp noob so any tips would be appreciated ;)

Explanation:

(defun fib(n x y)                                  | Define a function taking 3 arguments
                 (if(= 0 n)x                       | If n = 0, return x
                            (fib(1- n)y(+ x y))))  | Otherwise, call fib with n-1, y, and x+y

Bolce Bussiere

Posted 2017-05-17T13:45:49.483

Reputation: 970

2

br**nfuck, 39 29 bytes

Thanks to @JoKing for -10!

,<,<,[>[>+>+<<-]<[>+<-]>-]>>.

TIO won't work particularly well for this (or for any BF solution to a problem involving numbers). I strongly suggest @Timwi's EsotericIDE (or implementing BF yourself).

Takes x, then y, then n. 0-indexed. Assumes an unbounded or wrapping tape.

Explanation

,<,<,            Take inputs. Tape: [n, y, x]
[                While n:
  > [->+>+<<]      Add y to x, copying it to the next cell along as well. Tape: [n, 0, x+y, y]
  < [>+<-]         Move n over. Tape: [0, n, x+y, y]
  >-               Decrement n.
] >>.            End loop. Print cell 2 to the right (x for n == 0).

Khuldraeseth na'Barya

Posted 2017-05-17T13:45:49.483

Reputation: 2 608

Why do you bother moving x and y when you can just move n? Try It Online

– Jo King – 2018-04-21T23:07:13.727

@JoKing Considered that (but longer on my own), but it doesn't quite work, unless OP allows "-1-indexing". – Khuldraeseth na'Barya – 2018-04-21T23:35:24.167

Oh, just add a > to the end or swap x and y order – Jo King – 2018-04-21T23:48:17.607

@JoKing My palm hit my face quite hard just now. Thanks! – Khuldraeseth na'Barya – 2018-04-21T23:53:35.737

Why did you bother to censor "brain" but not the second word in the programming language's name? – MilkyWay90 – 2019-03-12T16:51:02.917

2

C (gcc), 29 bytes

f(n,x,y){n=n?f(n-1,y,x+y):x;}

Try it online!

This implementation is 0-based.

PikalaxALT

Posted 2017-05-17T13:45:49.483

Reputation: 41

Nice, and welcome! Here's a prettier TIO setup for testing, should you choose to use it.

– Khuldraeseth na'Barya – 2018-04-22T00:19:42.170

1

05AB1E, 9 bytes

`©GDŠ+}®@

Try it online!

Explanation

`           # split inputs as separate to stack
 ©          # store n in register
  G         # n-1 times do
   D        # duplicate top of stack
    Š       # move down 2 places on stack
     +      # add top 2 values of stack
      }     # end loop
       ®@   # get the value nth value from the bottom of stack

Emigna

Posted 2017-05-17T13:45:49.483

Reputation: 50 798

1

Lua, 44 bytes

0-Indexed

n,x,y=...for i=1,n do
x,y=y,x+y
end
print(x)

Try it online!

Felipe Nardi Batista

Posted 2017-05-17T13:45:49.483

Reputation: 2 345

1

Axiom, 88 57 bytes

f(k,x,y)==(repeat(k<=0=>break;c:=y;y:=x+y;x:=c;k:=k-1);x)

this would pass the test proposed (0 indexed)

(14) -> f(5,0,0)
   (14)  0
                                                 Type: NonNegativeInteger
(15) -> f(6,0,1)
   (15)  8
                                                    Type: PositiveInteger
(16) -> f(2,5,5)
   (16)  10
                                                    Type: PositiveInteger
(17) -> f(10,2,2)
   (17)  178
                                                    Type: PositiveInteger
(18) -> f(3,3,10)
   (18)  23
                                                    Type: PositiveInteger
(19) -> f(13,2308,4261)
   (19)  1325165
                                                    Type: PositiveInteger

RosLuP

Posted 2017-05-17T13:45:49.483

Reputation: 3 036

1

Klein, 18 + 3 bytes

This uses the 000 topology

:?\(:(+)$)1-+
((/@

Pass input in the form x y n.

Post Rock Garf Hunter

Posted 2017-05-17T13:45:49.483

Reputation: 55 382

1

Retina, 37 bytes

\d+
$*1
+`(1*) (1*) 1
$2 $1$2 
 .*

1

Try it online!

0-based, takes x y n separated by space. Calculates in unary.

eush77

Posted 2017-05-17T13:45:49.483

Reputation: 1 280

1

TI-Basic, 32 bytes

Prompt N,X,Y
While N
X+Y➡Z
Y➡X
Z➡Y
DS<(N,0
End
X

pizzapants184

Posted 2017-05-17T13:45:49.483

Reputation: 3 174

1

k, 15 bytes

{*x(|+\)/y,z-y}

Try it online!

zgrep

Posted 2017-05-17T13:45:49.483

Reputation: 1 291

1

Pari/GP, 24 bytes

n->x->(x*[0,1;1,1]^n)[1]

Input format: (n)([x,y]).

Try it online!

alephalpha

Posted 2017-05-17T13:45:49.483

Reputation: 23 988

1

AWK, 39 bytes

{for(n=3;n<$1+2;)$++n=$n+$(n-1);$0=$n}1

Try it online!

Takes inputs as n x y 0-indexed

Robert Benson

Posted 2017-05-17T13:45:49.483

Reputation: 1 339

1

Japt, 11 bytes

?ß´UWV+W :V

Try it online


Explanation

(Inputs U, V & W line up with n, x & y in the challenge.)
     :Implicit input of integer U.
?    :Ternary to check if U is currently >0.
ß    :If not, call the function again, with the arguments...
´U   :U-1,
W    :W,
V+W  :and V+W.
:    :Ternary "else", i.e. if U=0
V    :Return V

Shaggy

Posted 2017-05-17T13:45:49.483

Reputation: 24 623

1

Java, 58 bytes

int f(int n,int x,int y){return n<3?n<2?x:y:f(n-1,y,x+y);}

This function is 1-indexed.

Alternatively, one could write the following lambda with recursion, for 55 bytes:

interface B{F f=(n,x,y)->n<3?n<2?x:y:B.f.f(n-1,y,x+y);}

This requires the following description, which isn't usually counted in Java Lambdas:

interface F{int f(int n,int x,int y);}

Test

public class Main {

  static
  int f(int n,int x,int y){return n<3?n<2?x:y:f(n-1,y,x+y);}

  public static void main(String[] args) {
    int[][] tests = {
      {6, 0, 0, 0},
      {7, 0, 1, 8},
      {7, 1, 1, 13},
      {3, 5, 5, 10},
      {11, 2, 2, 178},
      {4, 3, 10, 23},
      {14, 2308, 4261, 1325165},
      {1, 0, 1, 0},
      {2, 0, 1, 1}
    };

    for (int[] test: tests) {
      System.out.printf("%2d %4d %4d %7d%n", test[0], test[1], test[2], f(test[0],test[1],test[2]));
    }
  }
}

Olivier Grégoire

Posted 2017-05-17T13:45:49.483

Reputation: 10 647

1

Mathematica, 25 bytes

Although this is quite old, and there has already been a Mathematica answer using LinearRecurrence built-in, mine solution is shorter.

{##2}.Fibonacci/@{#-1,#}&

user202729

Posted 2017-05-17T13:45:49.483

Reputation: 14 620

1

Forth (gforth), 30 bytes

: f 1- 0 ?do tuck + loop nip ;

Try it online!

Input Order is x y n

reffu

Posted 2017-05-17T13:45:49.483

Reputation: 1 361

1

Perl 6, 24 bytes

{($^x,$^y,*+*...*)[$^n]}

Try it online!

Sean

Posted 2017-05-17T13:45:49.483

Reputation: 4 136

1

SmileBASIC, 44 39 bytes

crossed out 44 is still regular 44 ;(

DEF F N,X,Y
IF!N THEN?X
F N-1,Y,X+Y
END

Recursive function; prints the result once N reaches 0, ends with a stack overflow.

12Me21

Posted 2017-05-17T13:45:49.483

Reputation: 6 110

1

Pyth, 23 bytes

J.)QWgJlQ=aQ+@Q_2eQ)@QJ

Test suite

0-indexed, input format: [x,y,n].

hakr14

Posted 2017-05-17T13:45:49.483

Reputation: 1 295

1

GolfScript, 8 bytes

~{.@+}*;

Try it online!

Takes input in order x y n. Actually generates first n+1 values and pops last.

Explanation:

~{.@+}*; Full program, implicit input
~        Evaluate
 {   }*  Pop n and repeat:    Stack: x y
  .        Duplicate y               x y y
   @       Get x                     y y x
    +      Add                       y x+y
       ; Pop last

wastl

Posted 2017-05-17T13:45:49.483

Reputation: 3 089

0

cQuents, 8 bytes

=A,B:z+y

Try it online!

Takes input as x y n, where n is 1-indexed.

Explanation

=A,B      Set sequence start to first two inputs
    :     Mode: Sequence
     z+y  Each item in the sequence is the previous two added together

          If there is a third input, that input is `n`. Get the `n`th (1-indexed) item in the sequence
          If there is not a third input, output the whole sequence.

Stephen

Posted 2017-05-17T13:45:49.483

Reputation: 12 293

Note current version uses Z and Y instead of z and y – Stephen – 2019-02-01T04:52:11.150