30
\$\begingroup\$

Challenge :

Pi is supposed to be infinite. That means every number is contained inside the decimal part of pi. Your task will be to take a positive integer on input and return the position of this number in pi digits on output.

For example, if the input is 59, we'll return 4

Here is why : we will look for the number 59 in the digits of pi

3.14159265...
     ^^

The value starts at the 4th digit, so the output will be 4.

Some other examples :

input : 1      output : 1
input : 65     output : 7
input : 93993  output : 42
input : 3      output : 9

Rules :

  • You don't have to handle digits that doesn't exist within the first 200 digits
  • Standard loopholes are, as always, forbidden.
  • This is , so the fewer bytes wins.
\$\endgroup\$
  • 41
    \$\begingroup\$ Numbers with the property you mention are known as normal numbers. An infinite decimal expansion, even if non-periodic, doesn't imply normality. 0.101001000100001... is a counterexample. \$\endgroup\$ – Dennis Apr 3 '18 at 14:21
  • 38
    \$\begingroup\$ And, absolutely, Pi is not supposed to be infinite. It's decimal representation, however, have infinite digits. \$\endgroup\$ – rafa11111 Apr 3 '18 at 14:22
  • 11
    \$\begingroup\$ @Dennis Normal is a much stronger condition (all-uniform vs all-exist) \$\endgroup\$ – user202729 Apr 3 '18 at 14:24
  • 6
    \$\begingroup\$ Are we allowed to output the 0-indexed n'th index? So the text cases would return 0, 6, 41, 8 instead of 1, 7, 42, 9. \$\endgroup\$ – Kevin Cruijssen Apr 3 '18 at 15:37
  • 7
    \$\begingroup\$ @rafa11111 I agree. We should abandon integers and use numbers in base-PI. Then integers will have infinite digits, instead. \$\endgroup\$ – mbomb007 Apr 3 '18 at 16:09

27 Answers 27

22
\$\begingroup\$

Python 2, 69 75 71 67 bytes

Saved 4 bytes due to caird coinheringaahing.

x=p=1333
while~-p:x=p/2*x/p+2*10**200;p-=2
print`x`.find(input(),1)

Not finding 3 at position zero cost 6 2 bytes. Input is given as a string.

Try it online!


Unbounded Version

Python 2, 224 bytes

def g():
 q,r,t,i,j=1,0,1,0,1
 while True:
  i+=1;j+=2;q,r,t=q*i,(2*q+r)*j,t*j;n=(q+r)/t
  if n*t>4*q+r-t:yield n;q,r=10*q,10*(r-n*t)
a=input()
l=len(`a`)
s=z=10**l;i=1-l
p=g().next;p()
while s!=a:s=(s*10+p())%z;i+=1
print i

Using an unbounded spigot based on the same formula used above.

Try it online!


Faster Version

from gmpy2 import mpz
def g():
  # Ramanujan 39, multi-digit
  q, r, s ,t = mpz(0), mpz(3528), mpz(1), mpz(0)
  i = 1
  z = mpz(10)**3511
  while True:
    n = (q+r)/(s+t)
    if n == (22583*i*q+r)/(22583*i*s+t):
      for d in digits(n, i>597 and 3511 or 1): yield d
      q, r = z*(q-n*s), z*(r-n*t)
    u, v, x = mpz(1), mpz(0), mpz(1)
    for k in range(596):
      c, d, f = i*(i*(i*32-48)+22)-3, 21460*i-20337, -i*i*i*24893568
      u, v, x = u*c, (u*d+v)*f, x*f
      i += 1
    q, r, s, t = q*u, q*v+r*x, s*u, s*v+t*x

def digits(x, n):
  o = []
  for k in range(n):
    x, r = divmod(x, 10)
    o.append(r)
  return reversed(o)

a=input()
l=len(`a`)
s=z=10**l;i=1-l
p=g().next;p()
while s!=a:s=(s*10+p())%z;i+=1
print i

A much faster unbounded spigot, based on Ramanujan #39.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Nice, neither hardcodes nor use built-in (because Python doesn't have any) \$\endgroup\$ – user202729 Apr 3 '18 at 15:04
  • 1
    \$\begingroup\$ Trivial 4 byte reduction \$\endgroup\$ – caird coinheringaahing Apr 3 '18 at 15:45
  • 2
    \$\begingroup\$ @Dennis 31 needs to match at 137 :/ \$\endgroup\$ – primo Apr 3 '18 at 15:45
  • 2
    \$\begingroup\$ Which approximation algorithm is this? Is it one listed here? en.wikipedia.org/wiki/Approximations_of_%CF%80 \$\endgroup\$ – Sphinxxx Apr 4 '18 at 1:11
  • 4
    \$\begingroup\$ @Sphinxxx it's the resullt of apply the Euler transform to the Leibniz series. I've posted a derivation in a previous post. \$\endgroup\$ – primo Apr 4 '18 at 4:16
19
\$\begingroup\$

Husk, 5 bytes

€tİπd

Try it online!

Explanation

€tİπd                              59
    d  Convert to base-10 digits   [5,9]
  İπ     The digits of pi          [3,1,4,1,5,9..]
 t       Remove the first element  [1,4,1,5,9,2..]
€      Index of the sublist        4
\$\endgroup\$
  • 1
    \$\begingroup\$ Ridiculous - but I have to admit I'm impressed. \$\endgroup\$ – Floris Apr 3 '18 at 19:29
  • 6
    \$\begingroup\$ With golfing languages it's usually a good idea to add an explanation, since someone who doesn't know the language won't be able to read it. If I understand correctly it's: Take the index of () with the first item (the leading 3) removed (t) of the digits of PI (İπ), convert it to base-10 (d) and output to STDOUT (implicitly). \$\endgroup\$ – Kevin Cruijssen Apr 4 '18 at 14:53
  • \$\begingroup\$ Agreed, I have no idea what I'm looking at. \$\endgroup\$ – J A Terroba Apr 5 '18 at 15:04
  • 1
    \$\begingroup\$ @gggg looks like it is a lazy representation example, verification \$\endgroup\$ – ASCII-only Apr 6 '18 at 5:52
  • 1
    \$\begingroup\$ @gggg İπ is an infinite list of digits, created with an unbounded spigot source \$\endgroup\$ – H.PWiz Apr 6 '18 at 13:46
18
\$\begingroup\$

Excel, 212 bytes

=FIND(A1,"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196")

Excel only handles 15 decimal places so pi is just hard-coded. This should be a pretty weak upper bound for this challenge.

\$\endgroup\$
  • 4
    \$\begingroup\$ I'm sorry to comment on my own post, but can some of the upvoters tell me why they like this answer? It's as golfed as it can be in an Excel formula but it's very long and not at all clever. \$\endgroup\$ – Engineer Toast Apr 3 '18 at 20:30
  • 6
    \$\begingroup\$ I like this because it doesn't rely on golfing languages which have builtins to calculate pi to an arbitrary decimal place. It may not be creative, but it's practical (not that practicality matters here). \$\endgroup\$ – Scott Apr 3 '18 at 20:51
  • \$\begingroup\$ As the question doesn't specify that the input or answer have to be base 10, could you golf this by using CONCAT and a BBP formula to calculate the first 200 digits of π-base16 and search in Hexadecimal instead? (Don't have 365, so can't test) \$\endgroup\$ – Chronocidal Apr 4 '18 at 9:47
  • 2
    \$\begingroup\$ Office 365 only: using CONCAT, CODE and MID I reduced the PI string from 202 characters (inc quotes) to 143: CONCAT(CODE(MID(".ÜÁ£ÙÏ ¦®š«¦ Ï²œÔ“ÇŧÝËŠº”ᱬ»—‡ÑÀ†œ¾ˆãÖœƒ°™¢•‘†ÏÒŽÐÖ³ ÒžÂ¯‰¦¬¼ß²º–ŸÈµ»¨Ñœ°‹‘­‚ÔŠ›ÝÕ•Š·»À®–Þٶ݃Ñà",2*ROW(A1:A100)-1,2))-32) \$\endgroup\$ – Chronocidal Apr 4 '18 at 10:05
  • 1
    \$\begingroup\$ Testing with Office365, it looks like it outputs 14 regardless of the input? \$\endgroup\$ – Matthew Schlachter Apr 4 '18 at 14:19
9
\$\begingroup\$

Java 8, 615 217 202 184 182 166 165 bytes (calculated 999 200 digits)

n->{var t=java.math.BigInteger.TEN.pow(200);var r=t;for(int p=667;p-->1;)r=t.valueOf(p).multiply(r).divide(t.valueOf(p-~p)).add(t).add(t);return(r+"").indexOf(n,1);}

1-indexed

Try it online.

Java's builtin Math.PI has a precision of 15 decimal values, like many other languages. To have more digits, you'll have to calculate them yourself with BigIntegers or BigDecimals. This above is a way to do it.. Maybe someone can golf this below 211 bytes, lol..
EDIT: Created a port of @primo's Python 2 answer (make sure to upvote him!), so calculating being shorter than hard-coded is not so far-fetched anymore. Just 7 more bytes to golf for it to be shorter.

-15 bytes thanks to @Neil, making it shorter than the hard-coded answer below!
-36 bytes thanks to @primo.
-1 byte changing java.math.BigInteger t=null,T=t.TEN.pow(200),r=T; to var T=java.math.BigInteger.TEN.pow(200);var r=T;, because var is 1 byte shorter than null (gotta love the new Java 10).

Explanation:

n->{                            // Method with String parameter and integer return-type
  var t=java.math.BigInteger.TEN.pow(200);
                                //  Temp BigInteger with value 10^200
  var r=t;                      //  Result BigInteger, also starting at 10^200
  for(int p=667;                //  Index-integer, starting at 667
      p-->1;)                   //  Loop as long as this integer is still larger than 1
                                //  (decreasing `p` by 1 before every iteration with `p--`)
    r=                          //   Replace the Result BigInteger with:
      t.valueOf(p)              //    `p`
       .multiply(r)             //    multiplied by `r`,
       .divide(t.valueOf(p-~p)) //    divided by `2*p+1`
       .add(t).add(t);          //    And add 2*10^200
  return(r+"")                  //  Convert the BigInteger to a String
    .indexOf(n,                 //  And return the index of the input,
               1);}             //  skipping the 3 before the comma

Java 8, 211 bytes (hard-coded 200 digits)

"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196"::indexOf

0-indexed

Try it online.

\$\endgroup\$
  • 1
    \$\begingroup\$ !p.equals(t.ONE) perhaps? Also, indexOf(n,1)-1 works I think. Or save 2 bytes and make it 1-indexed. \$\endgroup\$ – Neil Apr 3 '18 at 15:43
  • \$\begingroup\$ Not sure how I missed the first, but the second I really need to remember. Didn't knew there was an indexOf method that skips the first m characters. TIL, thanks! \$\endgroup\$ – Kevin Cruijssen Apr 3 '18 at 15:50
  • 1
    \$\begingroup\$ How about keeping p an integer? \$\endgroup\$ – primo Apr 3 '18 at 20:00
  • 1
    \$\begingroup\$ You can also decrement p by one each time (for(int p=667;p-->1;)), and then multiply by p and divide by p-~p. \$\endgroup\$ – primo Apr 4 '18 at 8:28
  • 1
    \$\begingroup\$ The initial value of r can literally be anything, although extreme values will require more iterations. The best seed (fewest iterations) is actually 4e200. \$\endgroup\$ – primo Apr 4 '18 at 10:02
6
\$\begingroup\$

05AB1E, 6 bytes

₁žs¦¹k

Try it online!

How?

₁        push 256
 žs      push pi to 256 places
   ¦     remove the leading 3
    ¹    push the input
     k   index inside that string
\$\endgroup\$
  • \$\begingroup\$ If I get the similar 6-byte solution in the same language, after you, do I delete my answer? \$\endgroup\$ – nicael Apr 3 '18 at 15:00
  • \$\begingroup\$ @nicael usually it doesn't matter, but your solution fails for 3 anyway \$\endgroup\$ – Uriel Apr 3 '18 at 15:01
  • \$\begingroup\$ Oh, indeed, thnks \$\endgroup\$ – nicael Apr 3 '18 at 15:02
6
\$\begingroup\$

MATL, 16 15 bytes

YP8WY$4L)jXfX<q

Try it online!

Explanation

YP     % Push pi as a double
8W     % Push 2^8, that is, 256
Y$     % Compute pi with 256 significant digits using variable-precision arithmetic
       % The result as a string
4L)    % Remove first character. This is to avoid finding '3' in the integer part
       % of pi
j      % Push input as a string
Xf     % Strfind: gives array of indices of occurrences of the input string in the
       % pi string
X<     % Mimimum
q      % Subtract 1. Implicitly display
\$\endgroup\$
  • \$\begingroup\$ Very nice and short ! Can you explain how it works ? \$\endgroup\$ – The random guy Apr 3 '18 at 14:36
  • \$\begingroup\$ @Therandomguy Sure, explanation added \$\endgroup\$ – Luis Mendo Apr 3 '18 at 14:37
4
\$\begingroup\$

R + numbers package, 52 bytes

regexec(scan(),substring(numbers::dropletPi(200),3))

Try it online!

dropletPi computes the first 200 decimal digits of pi but includes a 3. at the beginning, so we strip that out with substring and then match with regexec, which returns the index of the match along with some metadata about the match.

\$\endgroup\$
  • \$\begingroup\$ Maybe regexpr(scan(),numbers::dropletPi(200))-2? \$\endgroup\$ – djhurio Apr 3 '18 at 18:10
  • \$\begingroup\$ @djhurio that doesn't work because we have to match in the digits after the decimal point. That was my first thought as well but that case ruins it. Maybe an "if"? \$\endgroup\$ – Giuseppe Apr 3 '18 at 18:12
  • \$\begingroup\$ I do not see a problem here. Non of the input will contain 3. (I assume we deal with integers not reals in input). The test examples work with this. \$\endgroup\$ – djhurio Apr 3 '18 at 18:15
  • 3
    \$\begingroup\$ @djhurio right but regexpr(3,numbers::dropletPi(200))-2 returns -1 when it should return 9, try it \$\endgroup\$ – Giuseppe Apr 3 '18 at 18:16
3
\$\begingroup\$

Jelly, 23 bytes

⁵*⁹Ḥ;ȷḊ+J$¤×⁹:2¤:ɗ\SṾḊw

A monadic link accepting a list of characters (the integer to find) and returning the index. Works for inputs contained within the first 252 digits of the decimal part of π.

Try it online!

How?

This uses the Leibniz formula for π to calculate the first 253 digits including the leading 3 (plus four trailing incorrect digits). The leading 3 is then dropped and the index of the input is found:

⁵*⁹Ḥ;ȷḊ+J$¤×⁹:2¤:ɗ\SṾḊw - Link: list of characters
⁵                       - literal ten
  ⁹                     - literal 256
 *                      - exponentiate = 10000...0 (256 zeros)
   Ḥ                    - double       = 20000...0
          ¤             - nilad followed by links as a nilad:
     ȷ                  -   literal 1000
      Ḋ                 -   dequeue -> [2,3,4,5,...,1000]
         $              -   last two links as a monad:
        J               -     range of length -> [1,2,3,4,...,999]
       +                -     addition (vectorises) -> [3,5,7,9,...,1999]
    ;                   -   concatenate -> [20000...0,3,5,7,9,...,1999]
                  \     - cumulative reduce with:
                 ɗ      -   last three links as a dyad:
               ¤        -     nilad followed by link(s) as a nilad:
            ⁹           -       chain's right argument (the right of the pair as we traverse the pairs in the list -- 3, 5, 7, 9, ...)
              2         -       literal two
             :          -       integer division (i.e. 1, 2, 3, ...)
           ×            -     multiply (the left of the pair, the "current value", by that)
                :       -   integer divide by the right argument (i.e. 3, 5, 7, 9, ...)
                   S    - sum up the values (i.e. 20000...0 + 66666...6 + 26666...6 + 11428...2 + ... + 0)
                    Ṿ   - un-evaluate (makes the integer become a list of characters)
                     Ḋ  - dequeue (drop the '3')
                      w - first (1-based) index of sublist matching the input

If you prefer a list of digits as input use ⁵*⁹Ḥ;ȷḊ+J$¤×⁹:2¤:ɗ\SDḊw (also 23), while if you really want to give it an integer use ⁵*⁹Ḥ;ȷḊ+J$¤×⁹:2¤:ɗ\SDḊwD (for 24).

\$\endgroup\$
  • \$\begingroup\$ You mean Euler's transform applied to the Leibniz formula. Calculating 252 digits with the Leibniz formula would take a wee bit longer than most people would be willing to wait. \$\endgroup\$ – primo Apr 3 '18 at 20:30
  • \$\begingroup\$ Yes it would take a long time in raw form (it's still "using the Leibniz formula" I believe!) \$\endgroup\$ – Jonathan Allan Apr 3 '18 at 20:37
3
\$\begingroup\$

BASH (GNU/Linux), 75 67 66 bytes

Saved 1 byte thanks to Sophia Lechner, and 7 bytes thanks to Cows quack.

a=`bc -l<<<"scale=999;4*a(1)"|tail -c+2|grep -ob $1`;echo ${a%%:*}

This is a shell script that takes a single argument, which is the number. Test with

$ bash <script-path> 59
4

This script first executes a pipeline of three commands:

bc -l<<<"scale=999;4*a(1)"|    #produce pi with its first 999 fractional digits
tail -c+2|                     #cut off the "3."
grep -ob $1                    #compute the byte offsets of our argument in the string

The result of this pipeline is assigned to the shell variable a, which is then echoed out with anything but the first number removed:

a=`...`;         #assign the result of the pipeline to a variable
echo ${a%%:*}    #cleave off the first : character and anything following it

Unfortunately, bc has the tendency to break output lines when they become too long. This may lead to wrong results if the number to be found is not on the first line. You can avoid that by setting the environment variable BC_LINE_LENGTH:

export BC_LINE_LENGTH=0

This deactivates the line breaking feature completely.


Obviously, the last two commands may be omitted if other output is tolerated.
This gives a count of 48 bytes:

bc -l<<<"scale=999;4*a(1)"|tail -c+2|grep -ob $1

With the resulting output:

$ bash <script-path> 59
4:59
61:59
143:59
179:59
213:59
355:59
413:59
415:59
731:59
782:59
799:59
806:59
901:59
923:59
940:59
987:59
\$\endgroup\$
  • \$\begingroup\$ Nice! You don't need that space between -l and <<< though. \$\endgroup\$ – Sophia Lechner Apr 5 '18 at 0:10
  • \$\begingroup\$ You can convert to a program and use sed to save some bytes, Try it online! \$\endgroup\$ – Kritixi Lithos Apr 5 '18 at 6:53
  • \$\begingroup\$ @Cowsquack Wouldn't I need to include a shebang line in the byte count then? \$\endgroup\$ – cmaster Apr 5 '18 at 8:29
  • \$\begingroup\$ @cmaster shebang lines are not included in byte counts for any languages \$\endgroup\$ – Kritixi Lithos Apr 5 '18 at 9:29
  • \$\begingroup\$ @Cowsquack Thanks for the suggestion. However, if you allow for additional output, you might as well leave out the sed as well (see the second part of my answer). Nevertheless, transforming to a program gave me 7 bytes, so thanks for that! I have also replaced the tr/head combo with shell variable magic now to save another byte. \$\endgroup\$ – cmaster Apr 5 '18 at 10:36
2
\$\begingroup\$

JavaScript, 197 187

-10: Thanks, Neil!

x=>"50ood0hab15bq91k1j9wo6o2iro3by0h94bg3geu0dnnq5tcxz7lk62855h72el61sx7vzsm1thzibtd23br5tr3xu7wsekkpup10cek737o1gcr6t00p3qpccozbq0bfdtfmgk".replace(/.{9}/g,a=>parseInt(a,36)).search(x)+1

Takes a series of nine-digit base-36 integers, converts them to base 10, and concatenates them to create the first 200 digits of pi.

\$\endgroup\$
  • \$\begingroup\$ Nice, you blow my attempts at encoding the data out of the water, your approach saves 38 bytes on the raw data. \$\endgroup\$ – Nit Apr 3 '18 at 20:13
  • \$\begingroup\$ +1 - I was about to post the exact same approach. \$\endgroup\$ – darrylyeo Apr 3 '18 at 20:14
  • \$\begingroup\$ Use x=>'50...'.replace(/.{9}/g,a=>parseInt(a,36)).search(x)+1 to save 10 bytes. \$\endgroup\$ – Neil Apr 3 '18 at 20:54
2
\$\begingroup\$

First time doing code golf. Use delegates and lambda expressions to reduce the function calls. V2 shorten class name into a single byte.

[C#], 361 355 bytes

using System;class P{static void Main(){Func<string,int>F=f=>"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196".IndexOf(f)+1;Action<int>w=Console.WriteLine;w(F("1"));w(F("65"));w(F("93993"));w(F("3"));}}

Formatted version:

using System;

class P
{
    static void Main()
    {
        Func<string,int>F=f=>"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196".IndexOf(f)+1;
        Action<int>w=Console.WriteLine;
        w(F("1"));
        w(F("65"));
        w(F("93993"));
        w(F("3"));
    }
}

Ideone!

NB.I miscounted the first version. It was 361 bytes, not 363 bytes.

[C#], tio version 218 bytes

f=>"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196".IndexOf(f)+1

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You don't need to include the test cases in your code, and you can just use a lambda (anonymous) function instead of a full program \$\endgroup\$ – Zac Faragher Apr 4 '18 at 1:30
  • \$\begingroup\$ Hyarus suggested using System;f=>"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196".IndexOf(f)+1; as an edit. \$\endgroup\$ – ovs Apr 4 '18 at 8:30
  • \$\begingroup\$ I'm new here and I thought I must include a full program including the test case. It seems people are using tio.run for demonstration instead of ideone. I see that tio.run divide the code into parts. \$\endgroup\$ – Han Apr 4 '18 at 11:00
2
\$\begingroup\$

Haskell, 208 120 bytes

a=1333
x=tail$show$foldr(\p x->p`div`2*x`div`p+2*10^200)a[3,5..a]
x!n|take(length n)x==n=0|1<2=1+tail x!n
f n=1+x!show n

Try it online!

Many thanks to Jonathan Allan for his suggestions!

Old version (208 bytes)

(+1).((tail$g(1,0,1,1,3,3))!)
g(q,r,t,k,n,l)=([n:g(10*q,10*(r-n*t),t,k,div(10*(3*q+r))t-10*n,l)|4*q+r-t<n*t]++[g(q*k,(2*q+r)*l,t*l,k+1,div(q*(7*k+2)+r*l)(t*l),l+2)])!!0
x!n|take(length n)x==n=0|1<2=1+tail x!n

I actually don't know how the code above works; I've taken it from this paper and all I implemented was the lookup part. g(1,0,1,1,3,3) returns the digits of pi and is surprisingly efficient (it computes 10 000 digits on tio.run in less than 4s).

The input is a list consisting of the digits of the number to be found.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ My guess is that the Leibniz formula will be far shorter. \$\endgroup\$ – Jonathan Allan Apr 3 '18 at 18:04
  • \$\begingroup\$ @JonathanAllan Thanks! I will give it a try. I absolutely love this site! I've learned so much from you, guys! :) \$\endgroup\$ – Cristian Lupascu Apr 4 '18 at 6:09
  • \$\begingroup\$ @JonathanAllan I tried to approximate pi using l=4*sum[((-1)**x/(2*x+1))|x<-[0..1e6]], but that takes 5s to run and the 7th digit is already wrong. So it might not be feasible to compute 200 digits. It was an interesting exercise anyway, so thanks! \$\endgroup\$ – Cristian Lupascu Apr 4 '18 at 7:47
  • 1
    \$\begingroup\$ You'd want to use the Euler transform (see my Jelly answer or primo's Python answer) \$\endgroup\$ – Jonathan Allan Apr 4 '18 at 8:44
  • 1
    \$\begingroup\$ In reference to the paper you linked, you might be interested in this post, in which I re-implement the code found in this paper without "deliberate obfuscation." It's also quite a bit simpler (shorter) as a result. See method g1_ref in section Faster Unbounded Generators. The code is python. \$\endgroup\$ – primo Apr 4 '18 at 19:04
2
\$\begingroup\$

Haskell, 230 bytes

Using laziness to find the number anywhere in the infinite digits of pi, not just in the first 200 digits. Oh yeah, and it returns you every (infinitely many?) instance(s) of the number, not just the first one.

p=g(1,0,1,1,3,3)where g(q,r,t,k,n,l)=if 4*q+r-t<n*t then n:g(10*q,10*(r-n*t),t,k,div(10*(3*q+r))t-10*n,l) else g(q*k,(2*q+r)*l,t*l,k+1,div(q*(7*k+2)+r*l)(t*l),l+2)
z n=[(i,take n$drop i p)|i<-[1..]]
f l=[n|(n,m)<-z$length l,m==l]

Examples from the challenge

>  take 10 $ f [1]
[1,3,37,40,49,68,94,95,103,110]
>  take 10 $ f [6,5]
[7,108,212,239,378,410,514,672,870,1013]
>  take 1 $ f [9,3,9,9,3]
[42]
>  take 10 $ f [3]
[9,15,17,24,25,27,43,46,64,86]

Credits

'p' is the infinite stream of pi digits, taken from https://rosettacode.org/wiki/Pi#Haskell

> take 20 p
[3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4]
\$\endgroup\$
  • \$\begingroup\$ I guess you already know this, but you only need to output the first number in your sequence... \$\endgroup\$ – Timtech Apr 4 '18 at 21:35
  • \$\begingroup\$ Just thought I'd embrace the infinite-ness :D \$\endgroup\$ – tombop Apr 4 '18 at 21:36
2
\$\begingroup\$

SmileBASIC, 179 164 bytes

INPUT I$FOR I=0TO 103Q$=Q$+STR$(ASC("\A#YO &.+& O2TGE']KiRa1,;N(>VYb>P0*uCb0V3 RB/]T._2:H5;(Q0oJ2)&4n7;@.^Y6]&"[I]))NEXT?INSTR(Q$,I$)+1

Digits of pi are hardcoded and packed into the ascii values of characters. 14 -> CHR$(14), 15 -> CHR$(15), 92 -> \, 65 -> A, 35 -> #.

The string contains unprintable characters, so here are the bytes written in hexadecimal: 0E 0F 5C 41 23 59 4F 20 26 2E 1A 2B 26 20 4F 32 1C 54 13 47 45 27 5D 4B 69 52 00 61 31 2C 3B 17 00 4E 10 28 3E 56 14 59 62 3E 50 03 30 19 03 2A 75 00 43 62 15 30 00 56 33 20 52 1E 42 2F 00 5D 54 2E 00 5F 32 3A 16 1F 48 35 3B 28 51 1C 30 6F 4A 32 1C 29 00 1B 00 13 26 34 6E 37 3B 40 2E 16 5E 59 36 5D 00 26 13 06

In decimal, you can see the digits of pi: 14 15 92 65 35 89 79 32 38 46 26 43 38 32 79 50 28 84 19 71 69 39 93 75 105 82 0 97 49 44 59 23 0 78 16 40 62 86 20 89 98 62 80 3 48 25 3 42 117 0 67 98 21 48 0 86 51 32 82 30 66 47 0 93 84 46 0 95 50 58 22 31 72 53 59 40 81 28 48 111 74 50 28 41 0 27 0 19 38 52 110 55 59 64 46 22 94 89 54 93 0 38 19 6

\$\endgroup\$
  • \$\begingroup\$ If you post the complete code, it would make it easier to verify your answer. \$\endgroup\$ – primo Apr 3 '18 at 20:20
  • 1
    \$\begingroup\$ I can't post it because there are invalid characters that are removed/not displayed. I guess I can post the ascii codes though. \$\endgroup\$ – 12Me21 Apr 3 '18 at 20:28
  • \$\begingroup\$ You could post a hexdump, using xxd for example. \$\endgroup\$ – Nathaniel Apr 5 '18 at 5:02
2
\$\begingroup\$

Ruby, 37 35 bytes

p"#{BigMath::PI 200}"[3..-3]=~/#$_/

Try it online!

Nothing special, just showcasing the built-in library. Output is 0-indexed. The Pi string is formatted as 0.31415...e1, so we need to strip off the first 3 chars. The e1 part in the end doesn't really do any harm, but it is stripped off too, as we need to provide a range end (or slice length) value anyway.

\$\endgroup\$
  • \$\begingroup\$ short AND readable! \$\endgroup\$ – pjs Apr 4 '18 at 23:40
2
\$\begingroup\$

Charcoal, 27 15 bytes

I⊖∨⌕I▷N⟦≕Piφ⟧θχ

Try it online! Link is to verbose version of code. Works up to nearly 1000 digits. Explanation:

        ≕Pi     Get variable `Pi`
           φ    Predefined variable 1000
     ▷N⟦    ⟧   Evaluate variable to specified precision
    I           Cast to string
             θ  First input
   ⌕            Find
              χ Predefined variable 10
   ∨             Logical OR
  ⊖              Decrement
 I               Cast to string
                 Implicitly print
\$\endgroup\$
  • \$\begingroup\$ fixed, 13 bytes. side note: this feels really cheaty :P \$\endgroup\$ – ASCII-only Apr 4 '18 at 5:05
  • \$\begingroup\$ actually fixed, 13 bytes. uses implicit input. (not intended behavior but it seems more useful than any other way). also could you link to an example of the fill bug? \$\endgroup\$ – ASCII-only Apr 4 '18 at 5:13
  • \$\begingroup\$ @ASCII-only Fill weirdness - why does the cursor end up there? \$\endgroup\$ – Neil Apr 4 '18 at 8:07
  • \$\begingroup\$ :| oh i have no idea i should fix that asap \$\endgroup\$ – ASCII-only Apr 4 '18 at 23:47
  • \$\begingroup\$ nvm i'm an idiot, committed fix. \$\endgroup\$ – ASCII-only Apr 4 '18 at 23:51
2
\$\begingroup\$

Japt, 186 177 bytes

`nqnrvosrpruvtvpopuqsosqppÕÝvr¶uuqnvtnsvpvvptrnmruomvtqvqqrvopmÉæqÛàÑ$vvÔàmpqupqm¡vuqum«rnpopmssqtmvpuqqsmvrrmruoopÌÊprvqÛ$uqunnqr¶uqn¶tmnvpÔnmrrrvsqqsoovquvrqvpmpunvs`®c -#mÃbU

Since Japt shares Javascript's 15-digit Pi constraint and shoco, the encoding used by Japt, doesn't encode numbers, some shenanigans are required for compression.

Shortly explained, the beginning is the below string in encoded form:

"nqnrvosrpruvtvpopuqsosqppupotvrmouuqnvtnsvpvvptrnmruomvtqvqqrvopmtunsqmsousomuvvusoumpquorpqonntmstvuonqumusrnpouopmssqtmvpuqqsmvrrmruoopntorprvqmunouqunnntqrmouqnmotmnvpuronnmrrrvsqqsoovquvrqvpmpunvs"

Which is a string where each letter is 'm' + corresponding digit of pi. I tested the whole alphabet and that letter gives the best compression by a few bytes.

Backticks tell Japt to decode the string. The rest of it is pretty straightforward:

®c -#mÃbU
®          // Given the above string, map each letter
 c         // and return its charcode
   -#m     // minus the charcode of 'm', 109.
      Ã    // When that's done,
        bU // find the index of the implicit input U.

Outputs 0-based index of the matching fragment.
Shaved another two bytes off thanks to Oliver.

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Clever idea! You can replace £X with ® and } with à \$\endgroup\$ – Oliver Apr 6 '18 at 20:20
  • \$\begingroup\$ @Oliver Thanks a lot for those, I'm still learning Japt so all help is very appreciated. \$\endgroup\$ – Nit Apr 7 '18 at 7:52
  • 1
    \$\begingroup\$ You've been doing great so far! I was curious to see if there was a better offset than 109. I made a bruteforcer, and it turns out 109 is optimal. Nicely done :) \$\endgroup\$ – Oliver Apr 8 '18 at 0:52
  • \$\begingroup\$ @Oliver Thanks for that, I simply tried the whole a-z range manually since it wasn't too much work. :P \$\endgroup\$ – Nit Apr 8 '18 at 9:21
1
\$\begingroup\$

AWK -M , 131 119 117 bytes

Uses -M flag for arbitrary precision calculations. Added p=k=0 (5 bytes) to the TIO link to allow multi-line input

{CONVFMT="%.999f";PREC=1e3;for(p=k=0;k<1e3;)p+=(4/(8*k+1)-2/(8*k+4)-1/(8*k+5)-1/(8*k+6))/16^k++;$0=$1==3?9:index(p,$1)-2}1

Try it online!

Explanation:

{CONVFMT="%.999f";  # Allows 999 decimal digits to be used when numbers are convert to strings
PREC=1e3;           # Digits of precision to use for calculations
for(;k<1e3;)p+=(4/(8*k+1)-2/(8*k+4)-1/(8*k+5)-1/(8*k+6))/16^k++; # The most concise numerical calculation I could find. It doesn't converge  extremely rapidly, but it seems to work OK
$0=$1==3?9:index(p,$1)-2}  # Replace input line with either 9 or index-2
                           # since indices will either be 1 (meaning 3 was input) or >= 3
1                   # Print the "new" input line
\$\endgroup\$
  • \$\begingroup\$ My first attempt used sprintf to get the decimals. Using CONVFMT is definitely cleaner. \$\endgroup\$ – Robert Benson Apr 3 '18 at 18:44
  • 2
    \$\begingroup\$ No need to use the flag: meta consensus is to consider this a language distinct from AWK, "AWK with -M flag" \$\endgroup\$ – Giuseppe Apr 3 '18 at 18:55
  • \$\begingroup\$ Good to know. I guess I should spend more time on meta... with my loads of free time. :) \$\endgroup\$ – Robert Benson Apr 3 '18 at 19:29
1
\$\begingroup\$

Jelly, 24 bytes

ȷ*
ȷR×¢:Ḥ‘$ƲU×:¢+¢ʋ/ḤṾḊw

Try it online!

Use a Machin-like formula, specifically 1/4 pi == tan-1(1/2) + tan-1(1/3).

Use the formula pi/2 == 1 + 1/3 × (1 + 2/5 × (1 + 3/7 × (1 + 4/9 × ( ... ))))

\$\endgroup\$
  • \$\begingroup\$ Is there a way to get digits from ØP in M? \$\endgroup\$ – dylnan Apr 3 '18 at 17:22
  • \$\begingroup\$ @dylnan Somewhat, but M is not Jelly. \$\endgroup\$ – user202729 Apr 4 '18 at 2:19
  • \$\begingroup\$ I know they're different. Can't believe I didn't think of floor. Mind if I use that to post as answer in M? \$\endgroup\$ – dylnan Apr 4 '18 at 18:16
  • \$\begingroup\$ Nevermind. Doesn't work above 104 digits... \$\endgroup\$ – dylnan Apr 4 '18 at 18:19
1
\$\begingroup\$

Python 2 239 238 229 214 bytes

-9 bytes due to @primo

from bigfloat import*;a=s=n=10**10**5;b=k=0
while a:k+=1;a*=k*(k*(108-72*k)-46)+5;a/=k**3*(640320**3/24);s+=a;b+=k*a
with precision(10**7):print`(426880*sqrt(10005*n)*n)/(13591409*s+545140134*b)`.find(input())-16

Uses the Chudnovsky-Ramanujan algorithm to find the first 1 million digits 50000 digits of π (change 10**10**5 to 10**10**6 for more, but it takes ages to run) and then searches them for the desired string.

\$\endgroup\$
  • \$\begingroup\$ I tried to confirm the result but it doesn't seem to terminate (n=10**10**5 takes about 10s). \$\endgroup\$ – primo Apr 5 '18 at 11:15
  • \$\begingroup\$ @primo I never said it was fast! 10**10**6 takes about 7 minutes on my machine.. To be fair, 10**10**5 gives the first 50000 digits, so I guess it's not that bad either :) \$\endgroup\$ – DividedByZero Apr 5 '18 at 13:29
  • \$\begingroup\$ @primo I've changed the arbitrary precision library to bigfloat, it runs much quicker now. \$\endgroup\$ – DividedByZero Apr 5 '18 at 15:39
  • \$\begingroup\$ It's much faster now, I was going to suggest switching to gmpy2, but bigfloat saves a dozen or so bytes. The assignment of k can be merged with k=b=0 if you move k+=1 to the start of the iteration. -(6*k-5)*(2*k-1)*(6*k-1) can be written more succinctly as k*(k*(108-72*k)-46)+5. If you declare Python 2, the // integer divisions can be replaced by /, and also parentheses aren't necessary for print. Space can also be removed in import*. Only validates to 50000 digits, btw. \$\endgroup\$ – primo Apr 5 '18 at 18:07
  • \$\begingroup\$ The n in sqrt(10005*n) seems to be the problem; it's moving the decimal point to 50000th place. In case you're interested, here's my own Chudnovsky implementation: Try it online! \$\endgroup\$ – primo Apr 5 '18 at 18:21
1
\$\begingroup\$

Visual Basic - 114 Bytes

Okay, first submission. Go easy on me!

    Dim s,p As String
    s=Console.Readline()
    p=Math.PI
    Console.Write((p.IndexOf(s,2)-1))

Feedback welcome!

I haven't restricted to the first 256 parts of PI as the question says "You don't have to", not "You shouldn't" Hope I'm doing this right :)

\$\endgroup\$
  • \$\begingroup\$ I don't know much about virtual basic, but i guess you can save some bytes by removing all the spaces. You also should be able to store your code into a function and return the value instead of "console.log" it (i guess you would gain some bytes like that). Oh, and you have to input the value and not hardcode it. \$\endgroup\$ – The random guy Apr 6 '18 at 14:46
  • \$\begingroup\$ Thanks. Removed spaces and removed the hardcoded value in favour of input. Increases the count to 114! Would the function for returning the value not be included in the byte count? I imagine it would make it longer if so. \$\endgroup\$ – user9338709 Apr 6 '18 at 14:55
  • \$\begingroup\$ Welcome to the site! This looks like it works (try it online!), but it appears to be a snippet and submissions need to be either a full program, or a function. \$\endgroup\$ – Dom Hastings Apr 6 '18 at 15:26
  • \$\begingroup\$ Something like this might work, but there are probably better ways to do the things! Check out the link menu at the top of that page for the template a lot of submissions use! \$\endgroup\$ – Dom Hastings Apr 6 '18 at 15:26
  • \$\begingroup\$ Actually, it looks like the constant doesn't have 200 digits :( Try it online! - this should return 197. \$\endgroup\$ – Dom Hastings Apr 6 '18 at 15:30
0
\$\begingroup\$

Javascript 217 bytes (200 hardcoded)

a=>"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196".search(a)+1
\$\endgroup\$
0
\$\begingroup\$

PHP, 27 bytes

Not a very serieus answer, it requires a change in the php.ini settings as pi() defaults to 14 digits, not 200, but for once the PHP solution is fairly elegant:

<?=strpos(pi(),$_GET[n])-1;
\$\endgroup\$
  • \$\begingroup\$ I don't think this will actually work. the precision tag in php.ini only alters the display precision, and doesn't actually increase the precision of defined constants. witness \$\endgroup\$ – primo Apr 5 '18 at 9:11
0
\$\begingroup\$

Julia 0.6, 53 bytes

setprecision(9^6)
x->searchindex("$(big(π))","$x",3)

Set the precision for BigFloats high enough, then convert pi to a string and search. Precision of 9^6 handles 159980 digits.

Try it online!

\$\endgroup\$
0
\$\begingroup\$

J, 25 Bytes

{.I.(}.":<.@o.10x^999)E.~

Try it online!

0-Indexed

Takes input as a string, +2 Bytes (":) if that's not allowed.

Explanation eventually.

\$\endgroup\$
0
\$\begingroup\$

Perl 5 with -MMath::BigFloat+bpi and -n, 20 bytes

bpi($>)=~/.$_/;say@-

Try it online!

I'm not sure where usage of $> stands, since it's the EFFECTIVE_USER_ID which is not portable, but on TIO this is 1000 and satisfies our requirement, for -1 byte vs. 200.

\$\endgroup\$
0
\$\begingroup\$

Husk, 5 bytes

€tİπd

Try it online!

€        The 1-based index as a substring of
    d    the decimal digits of
         the input
  İπ     in the infinite list of digits of pi
 t       after the radix point.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.