Print the nth Fibonacci number containing the nth Fibonacci number!

22

0

Challenge

You must write a program that takes a positive integer n as input, and outputs the nth Fibonacci number (shortened as Fib# throughout) that contains the nth Fib# as a subtring. For the purposes of this challenge, the Fibonacci sequence begins with a 1.

Here are some examples that you can use as test cases, or as examples to clarify the challenge (for the latter, please leave a comment down below explaining what you find unclear).

n=1
Fib#s: 1
       ^1 1st Fib# that contains a 1 (1st Fib#)
Output: 1

n=2
Fib#s: 1, 1
       ^1 ^2 2nd Fib# that contains a 1 (2nd Fib#)
Output: 1

n=3
Fib#s: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233
             ^1              ^2                   ^3 3rd Fib# that contains a 2 (3rd Fib#)
Output: 233

n=4
Output: 233

n=5
Output: 6765

n=6
Output: 28657

n=7
Output: 1304969544928657

n=8
Output: 14472334024676221

n=9
Output: 23416728348467685

n=10
Fib#s: 1, ..., 34, 55, 89, ..., 63245986, 102334155, 165580141, ..., 2880067194370816120, 4660046610375530309
                   ^1                     ^2         ^3                                   ^10 10th Fib# that contains a 55 (10th Fib#)
Output: 4660046610375530309

As always, this is , so go for the lowest byte count possible.

If something is confusing/unclear, please leave a comment.

(This challenge is based off another challenge I posted: Print the nth prime that contains n)

ericw31415

Posted 2017-06-15T01:00:31.340

Reputation: 2 229

3I recommend including the n=5 testcase, because I just made a silly error where I wrote a check which counted a number several times if it had the substring more than once. n=5 would catch that because of the 55. – Ørjan Johansen – 2017-06-15T03:11:50.040

What are the constraints of n? – officialaimm – 2017-06-15T05:02:19.020

2@officialaimm I don't think it's reasonable to expect very high numbers. My solution works on TIO up to n=25 (the output has 1186 digits), then gets killed for n=26 (3085 digits compiled on my own laptop). There seems to be a jump in difficulty whenever fib(n) gets one more digit (as one would expect). The next jump, 31, has 12990 digits in the final output. – Ørjan Johansen – 2017-06-15T05:52:13.160

1Yes. Lol! my python solution gets stuck for n>6 because there is a recursive function which is called many times in a loop. :D – officialaimm – 2017-06-15T05:57:01.593

1@officialaimm Oh right, exponential blowup is a problem when defining Fibonacci directly with recursion. Even without that you might hit Python's recursion limit rather soon. – Ørjan Johansen – 2017-06-15T06:05:18.283

Can we consider 0 to be a Fibonacci number for the purposes of this challenge? Can we use 0-indexing? Can you add test cases for 4-9? – Shaggy – 2017-06-15T09:18:11.163

@Shaggy: The standard convention these days is to consider 0 as the 0th Fibonacci number. This is consistent with the examples in the question. – ShreevatsaR – 2017-06-15T12:41:09.827

@ShreevatsaR, the test cases appear to be using 1-indexing with 1 as the first number in the sequence. – Shaggy – 2017-06-15T13:00:06.287

1@Shaggy: That's what I meant by consistent: when 0 is the 0th Fibonacci number, then 1 is the first ("1th"?) Fibonacci number. – ShreevatsaR – 2017-06-15T13:07:16.143

I tried this in Taxi and got TIO to print the nth Fibonacci number with this program but is only accurate up to the 48th Fibonacci number and I have no idea why. This was going to be phase 1 in a ridiculously complicated Taxi solution but not if I can't figure out the problem first.

– Engineer Toast – 2017-06-15T17:43:57.040

@Shaggy I have added test cases 4 through 9. Since you're just using them as test cases, and not challenge clarification, I only put the required output. I hope that's OK. – ericw31415 – 2017-06-15T20:56:45.763

@officialaimm You could always just use the formula if you don't want to do it recursively. That might take more bytes though. – ericw31415 – 2017-06-15T21:00:03.900

Yes. I have already posted iterative solution for python. Check it out! – officialaimm – 2017-06-15T21:37:43.597

1@officialaimm Yeah, I saw it. I meant that there's an equation to find the nth term. It's faster, but takes more bytes. – ericw31415 – 2017-06-15T22:25:18.793

@EngineerToast That's just about the right size to break if your ints are 32 bits. fib(48)==4807526976, 2^32==4294967296. – Ørjan Johansen – 2017-06-15T23:46:13.583

@ØrjanJohansen That makes a lot of sense, thanks. I don't know if it's Taxi or TIO with that limitation. Ah, well. – Engineer Toast – 2017-06-16T12:20:32.897

Answers

12

Haskell, 85 84 bytes

EDIT:

  • -1 byte: Laikoni shortened l.
  • Typo (x>=s for x<=s) in explanation.

f takes an Int and returns a String.

l=0:scanl(+)1l
m=show<$>l
f n|x<-m!!n=[y|y<-x:m,or[x<=s|s<-scanr(:)""y,x++":">s]]!!n

Try it online!

How it works

  • l is the infinite list of Fibonacci numbers, defined recursively as the partial sums of 0:1:l. It starts with 0 because lists are 0-indexed. m is the same list converted to strings.
  • In f:
    • n is the input number, and x is the (string of the) nth Fibonacci number.
    • In the outer list comprehension, y is a Fibonacci number tested for whether it contains x as a substring. The passing ys are collected in the list and indexed with the final !!n to give the output. An extra x is prepended to the tests to save two bytes over using !!(n-1) at the end.
    • To avoid counting ys several times, the tests of each y are wrapped in or and another list comprehension.
    • In the inner list comprehension, s iterates through the suffixes of y.
    • To test whether x is a prefix of s, we check whether x<=s and x++":">s. (":" is somewhat arbitrary but needs to be larger than any numeral.)

Ørjan Johansen

Posted 2017-06-15T01:00:31.340

Reputation: 6 914

1l=0:scanl(+)1l saves a byte. – Laikoni – 2017-06-15T06:54:29.980

10

Jelly, 15 14 bytes

1 byte thanks to Jonathan Allan.

0µ³,ÆḞẇ/µ³#ÆḞṪ

Try it online!

Leaky Nun

Posted 2017-06-15T01:00:31.340

Reputation: 45 011

4

Python 2, 99 86 bytes

  • Ørjan Johansen Saved 7 bytes: starting with b=i=x=-1 a=1 and dropping the x and
  • Ørjan Johansen again saved 3 bytes: f and n==2 to f*(n>2)
  • Felipe Nardi Batista saved 9 bytes: economic swap a,b=a+b,a shorthand f-=str(x)in str(a), squeezed (n<2)*f
  • ovs saved 13 bytes: transition from python 3 to python 2.
f=n=input()
b=i=x=-1
a=1
while(n>2)*f:i+=1;a,b=a+b,a;x=[x,a][i==n];f-=`x`in`a`
print a

Try it online!

Explanation:

f=n=int(input())                 # f is number of required numbers

b=i=x=-1                         # i is index(counter) set at -1
                                 # In Two-sided fibonacci, fib(-1) is 1 
                                 # and b(fib before it) i.e. fib(-2) is -1
                                 # Taking advantage of all -1 values, x is 
                                 # also set to -1 so that the `if str(...`
                                 # portion does not execute until x is set a 
                                 # value(i.e. the nth fibonacci) since there 
                                 # is no way -1 will be found in the number 
                                 # (ALL HAIL to Orjan's Genius Idea of using 
                                 # two-sided fibonacci)      

a=1                              # fib(-1) is 1


while(n>2)*f:                    # no need to perform this loop for n=1 and 
                                 # n=2 and must stop when f is 0

 i+=1                            # increment counter

 b,a=a,a+b                       # this might be very familiar (fibonacci 
                                 # thing ;))                         

 x=[x,a][i==n]                   # If we have found (`i==n`) the nth 
                                 # fibonacci set x to it

 f-=`x`in`a`                     # the number with required substring is 
                                 # found, decrease value of f

print a                          # print required value

Python 3, 126 120 113 112 110 101 99 bytes

f=n=int(input())
b=i=x=-1
a=1
while(n>2)*f:i+=1;a,b=a+b,a;x=[x,a][i==n];f-=str(x)in str(a)
print(a)

Try it online!

officialaimm

Posted 2017-06-15T01:00:31.340

Reputation: 2 739

1You can get rid of 7 more bytes by starting with b=i=x=-1 a=1 and dropping the x and. (Essentially starting 3 steps earlier in the two-sided Fibonacci sequence -1, 1, 0, 1, 1, 2, ....) – Ørjan Johansen – 2017-06-15T07:01:18.803

Thanks a lot!!. But I only got it down by 6. – officialaimm – 2017-06-15T07:15:47.533

1You left a space at the end of -1 :P – Ørjan Johansen – 2017-06-15T07:16:45.273

Updated the explanation. That was hard one. ;) Take a look and let me know if it makes sense. – officialaimm – 2017-06-15T07:36:42.583

1Erm blush. Also, I want to get rid of and n>2 but it seems n==2 really needs special treatment. But it can be shortened to *(n>2). – Ørjan Johansen – 2017-06-15T08:12:34.290

1

golfed it down to 88 bytes, some changes are exclusive to python 2. but the rest will work in python 3 as well

– Felipe Nardi Batista – 2017-06-15T11:07:53.843

@FelipeNardiBatista Woah! Thanks a lot! I wish python 3 had \a``. You can post an answer for python 2 btw just cite my answer. ;) – officialaimm – 2017-06-15T11:21:58.063

1

for python 3, you can still golf 9 bytes: here

– Felipe Nardi Batista – 2017-06-15T11:24:28.197

1

last thing :P you can make your while into one line and shave 2 more bytes

– Felipe Nardi Batista – 2017-06-15T11:28:04.587

Nice. But I just updated to the same length and much clean-looking check!

– officialaimm – 2017-06-15T11:41:03.567

1You can do the same thing in 86 bytes with Python 2 – ovs – 2017-06-15T12:13:41.497

@ovs Can I submit another python 2 answer? – officialaimm – 2017-06-15T13:51:48.370

1@officialaimm While you could do it, it will be better received if you edit this answer or add the python 2 version to your current answer – ovs – 2017-06-15T14:17:38.090

4

Java, 118 111 bytes

i->{long n=i,p=0,q,c=1;for(;--n>0;p=c,c+=q)q=p;for(n=c;i>0;q=p,p=c,c+=q)if((""+c).contains(""+n))--i;return p;}

I keep thinking it should be possible not to duplicate the Fibonacci bit, but all my efforts somehow result in more bytes.

Thanks to Kevin for improvements... guess it shows this was my first attempt at golfing :)

laszlok

Posted 2017-06-15T01:00:31.340

Reputation: 141

2Snippets are not allowed. You should turn this into a lambda like so: i->{long n=i,p=0,q,c=1;while(--n>0){q=p;p=c;c+=q;}n=c;while(i>0){if((""+c).contains(""+n))--i;q=p;p=c;c+=q;}return p;} (118 bytes) – Okx – 2017-06-15T09:40:23.227

1

Welcome to PPCG! After you've changed it to a lambda as @Okx pointed out, I must say it's an impressive answer. I tried to do this challenge about an hour ago just before lunch, and gave up. So +1 from me. Some small things to golf: while(--n>0){q=p;p=c;c+=q;} can be for(;--n>0;p=c,c+=q)q=p; and n=c;while(i>0){if((""+c).contains(""+n))--i;q=p;p=c;c+=q;} can be for(n=c;i>0;q=p,p=c,c+=q)if((""+c).contains(""+n))--i;. (In total: i->{long n=i,p=0,q,c=1;for(;--n>0;p=c,c+=q)q=p;for(n=c;i>0;q=p,p=c,c+=q)if((""+c).contains(""+n))--i;return p;} (111 bytes)

– Kevin Cruijssen – 2017-06-15T11:02:52.720

2

Perl 6, 45 bytes

{my@f=0,1,*+*...*;@f.grep(/$(@f[$_])/)[$_-1]}

$_ is the argument to the function; @f is the Fibonacci sequence, lazily generated.

Sean

Posted 2017-06-15T01:00:31.340

Reputation: 4 136

2

JavaScript (ES6), 96 93 92 90 86 bytes

0-indexed, with the 0th number in the sequence being 1. Craps out at 14.

f=(n,x=1,y=1)=>n?f(n-1,y,x+y):x+""
g=(n,x=y=0)=>x>n?f(y-1):g(n,x+!!f(y++).match(f(n)))
  • 2 6 bytes saved thanks to Arnauld

Try it

f=(n,x=1,y=1)=>n?f(n-1,y,x+y):x+""
g=(n,x=y=0)=>x>n?f(y-1):g(n,x+!!f(y++).match(f(n)))
oninput=_=>o.innerText=(v=+i.value)<14?`f(${v}) = ${f(v)}\ng(${v}) = `+g(v):"Does not compute!"
o.innerText=`f(0) = ${f(i.value=0)}\ng(0) = `+g(0)
<input id=i min=0 type=number><pre id=o>

Explanation

Updated version to follow, when I get a minute.

f=...                   :Just the standard, recursive JS function for generating the nth Fibonacci number
g=(...)=>               :Recursive function with the following parameters.
n                       :  The input integer.
x=0                     :  Used to count the number of matches we've found.
y=0                     :  Incremented on each pass and used to generate the yth Fibonacci number.
x>n?                    :If the count of matches is greater than the input then
f(y-1)                  :    Output the y-1th Fibonacci number.
:                       :Else
g(...)                  :    Call the function again, with the following arguments.
n                       :      The input integer.
x+                      :      The total number of matches so far incremented by the result of...
RegExp(f(n)).test(f(y)) :        A RegEx test checking if the yth Fibonacci number, cast to a string, contains the nth Fibonacci number.
                        :        (returns true or false which are cast to 1 and 0 by the addition operator)
y+1                     :      The loop counter incremented by 1

Shaggy

Posted 2017-06-15T01:00:31.340

Reputation: 24 623

Your answer seems to provide different output from the examples. – ericw31415 – 2017-06-15T22:33:40.167

@ericw31415, that's because it's 0-indexed. – Shaggy – 2017-06-15T22:48:36.563

I wrote specifically wrote this though: "For the purposes of this challenge, the Fibonacci sequence begins with a 1." – ericw31415 – 2017-06-16T00:25:07.330

@ericw31415: And my sequence does begin with 1, it's just 0-indexed; the 0th and 1st numbers in the sequence are 1, the 2nd is 2, the 3rd is 3, the 4th is 5, the 5th is 8, and so on, and so forth. – Shaggy – 2017-06-16T08:07:45.437

2

Charcoal, 65 bytes

AIθνAνφA±¹βAβιAβξA¹αW∧›ν²φ«A⁺ι¹ιA⁺αβχAαβAχαA⎇⁼ιναξξA⁻φ›№IαIξ⁰φ»Iα

Try it online! Link to verbose code for explanation.

ASCII-only

Posted 2017-06-15T01:00:31.340

Reputation: 4 687

1

Mathematica, 85 bytes

(i=ToString;f=Fibonacci;For[n=t=0,t<#,If[i@f@n++~StringContainsQ~i@f@#,t++]];f[n-1])&

input

[10]

-4 bytes from @JungHwan Min

output

4660046610375530309

J42161217

Posted 2017-06-15T01:00:31.340

Reputation: 15 931

2Looks weird but f@i@n++ is totally valid, decreasing 1 byte. Using For instead of While reduces 3 bytes. 85 bytes: (i=ToString;f=Fibonacci;For[n=t=0,t<#,If[i@f@n++~StringContainsQ~i@f@#,t++]];f[n-1])& – JungHwan Min – 2017-06-15T03:29:46.683

Just a heads up, declaring global variables separately is completely fine. My bad.

– JungHwan Min – 2017-06-15T15:15:56.353

1

R, 77 72 bytes

F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)

This makes use of the gmp library for the Fibonacci number. Fairly straight foward implementation of the question.

F=gmp::fibnum;          # Alias Fibonacci function to F
i=0;                    # intitalise counter
d=n=scan();             # get n assign to d as well
while(n)               # loop while n
  if(grepl(F(d),F(i<-i+1)))  # use grepl to determine if Fib of input is in Fib# and increment i
     n=n-1;             # decrement n
F(i)                  # output result

Some tests

> F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)
1: 2
2: 
Read 1 item
Big Integer ('bigz') :
[1] 1
> F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)
1: 3
2: 
Read 1 item
Big Integer ('bigz') :
[1] 233
> F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)
1: 10
2: 
Read 1 item
Big Integer ('bigz') :
[1] 4660046610375530309
> F=gmp::fibnum;i=0;d=n=scan();while(n)if(grepl(F(d),F(i<-i+1)))n=n-1;F(i)
1: 15
2: 
Read 1 item
Big Integer ('bigz') :
[1] 1387277127804783827114186103186246392258450358171783690079918032136025225954602593712568353

MickyT

Posted 2017-06-15T01:00:31.340

Reputation: 11 735

1

PHP, 96 bytes

for($f=[0,1];$s<$a=$argn;$s+=$f[$a]&&strstr($f[$i],"$f[$a]")?:0)$f[]=$f[$i]+$f[++$i];echo$f[$i];

Try it online!

Jörg Hülsermann

Posted 2017-06-15T01:00:31.340

Reputation: 13 026

0

Clojure, 99 bytes

(def s(lazy-cat[0 1](map +(rest s)s)))#(nth(filter(fn[i](.contains(str i)(str(nth s %))))s)(dec %))

A basic solution, uses an infinite sequence of Fibonacci numbers s.

NikoNyrh

Posted 2017-06-15T01:00:31.340

Reputation: 2 361

0

C#, 35 bytes

int u=1,b=1;for(;b<n;){b+=u;u=b-u;}

Try it

int n=int.Parse(t2.Text);int u=1,b=1;for(;b<n;){b+=u;u=b-u;t.Text+=b.ToString()+" ";}if(b==n){t.Text+="true";}

Erlantz Calvo

Posted 2017-06-15T01:00:31.340

Reputation: 131

1Welcome on Programming Puzzle and Code-Golf. Answers need to be either a full program or a function, while you only provided a snippet. In particular, you are assuming that the input is in n and you just put the output in b (I think). You could write that take n as arguments and returns b... Also, I'm pretty sure you are not computing what the challenges asks for. Actually, I have no idea what you are computing. Could you please provide use with some code that we can run to verify your solution? (your "Try it" can't be run as is..) – Dada – 2017-06-19T09:53:29.490

0

NewStack, 14 bytes

N∞ ḟᵢfi 'fif Ṗf⁻

The breakdown:

N∞              Add all natural numbers to the stack
   ḟᵢ           Define new function will value of input
     fi          Get the n'th Fibonacci number for ever element n
       'fif      Remove all elements that don't contain the (input)'th Fibonacci number 
           Ṗf⁻  Print the (input-1)'th element

In English: (with example of an input of 3)

N∞: Make a list of the natural numbers [1,2,3,4,5,6...]

ḟᵢ: Store the input in the variable f [1,2,3,4,5,6...]

: Convert the list to Fibonacci numbers [1,1,2,3,5,8...]

'fif: Keep all elements that contain the fth Fibonacci number [2,21,233...]

Ṗf⁻: Print the f-1th element (-1 due to 0-based indexing) 233

Graviton

Posted 2017-06-15T01:00:31.340

Reputation: 2 295

The GitHub seems to contain only a readme and a tutorial. An implementation is referred to, but it's not linked. Although PPCG now allows languages newer than the challenge, I believe we still require a publically available implementation. – Ørjan Johansen – 2017-06-27T00:11:29.510

@ØrjanJohansen, Ahah thanks for reminding me. I forgot to upload that! It'll be up in a minute. – Graviton – 2017-06-27T04:48:13.120

Your implementation seems to use UTF-8, in which case that's actually 28 bytes (don't mind the Haskell setting, I'm only using TIO to count bytes). Languages like Jelly etc. have their own code pages for this reason.

– Ørjan Johansen – 2017-06-27T07:10:09.863

@ØrjanJohansen Touché, I'm in the works of distributing a table for it's own encoding as we speak. – Graviton – 2017-06-27T21:50:21.690

0

Japt, 16 15 bytes

_søNg)«´U}a@MgX

Try it

Shaggy

Posted 2017-06-15T01:00:31.340

Reputation: 24 623