Pi numaranı aldı


30

Meydan okuma :

Pi'nin sonsuz olması gerekiyordu. Bu, her sayının pi'nin ondalık bölümünün içinde bulunduğu anlamına gelir. Göreviniz, girişte pozitif bir tamsayı almak ve bu sayının çıkıştaki pi basamaklarındaki konumunu döndürmek olacaktır.

Örneğin, eğer girdi ise 59, geri döneceğiz.4

İşte nedeni:59 pi rakamındaki sayıyı arayacağız.

3.14159265...
     ^^

Değer 4. basamaktan başlar, bu yüzden çıkış olacaktır 4.

Diğer bazı örnekler:

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

Kurallar:

  • İlk 200 hanede bulunmayan rakamları kullanmak zorunda değilsiniz.
  • Standart boşluklar her zaman olduğu gibi yasaktır.
  • Bu , bu yüzden daha az bayt kazanır.

41
Bahsettiğiniz özelliğe sahip numaralar normal numaralar olarak bilinir . Sonsuz bir ondalık genişleme, periyodik olmasa bile normallik anlamına gelmez. 0.101001000100001 ... bir karşı örnekdür .
Dennis,

38
Ve kesinlikle, Pi edilir değil sonsuz olması gerekiyordu. Ancak ondalık gösterimi sonsuz rakamlara sahiptir.
rafa11111

11
@Dennis Normal çok daha güçlü bir durum (hepsi-tek olan vs hepsi-var)
user202729

6
0 indeksli ndizini çıkarmamıza izin var mı? Böylece metin davaları 0, 6, 41, 8yerine geri dönecekti 1, 7, 42, 9.
Kevin Cruijssen

7
@ rafa11111 Katılıyorum. Tamsayıları bırakmalı ve üs-PI'de sayıları kullanmalıyız. O zaman tamsayılar yerine sonsuz rakamlar olacaktır.
mbomb007

Yanıtlar:


22

Python 2, 69 75 71 67 bayt

Caird coinheringaahing nedeniyle 4 bayt kurtardı .

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

Görmediklerine 3pozisyonunda sıfır maliyeti 6 bayt. Giriş bir dize olarak verilir.

Çevrimiçi deneyin!


Sınırsız Sürüm

Python 2,224 bayt

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

Yukarıda kullanılan aynı formüle göre sınırlandırılmamış bir tıkaç kullanmak.

Çevrimiçi deneyin!


Hızlı sürüm

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

Ramanujan # 39'a dayanan çok daha hızlı sınırsız bir tıkaç .

Çevrimiçi deneyin!


Güzel, ne
kod kodları


2
@Dennis 31, 137: /
primo ile

2
Hangi yaklaşım algoritması bu? Burada listeleniyor mu? en.wikipedia.org/wiki/Approximations_of_%CF%80
Sphinxxx

4
@Sphinxxx, Euler dönüşümünü Leibniz serisine uygulamanın ürünüdür. Önceki bir yazıya bir türev yayınladım .
primo

19

Kabuğu , 5 bayt

€tİπd

Çevrimiçi deneyin!

açıklama

€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

1
Saçma - ama etkilendiğimi itiraf etmeliyim.
Floris

6
Golf dilleri ile genellikle bir açıklama eklemek iyi bir fikirdir, çünkü dili bilmeyen bir kişi onu okuyamaz. Doğru anladıysam: ( ) dizinini tPI ( İπ) basamağının ilk maddesi (baştaki 3) kaldırıldı ( ) ile alın, base-10 ( d) 'a dönüştürün ve STDOUT'a (örtük olarak) çıkarın .
Kevin Cruijssen

Kabul ediyorum, neye baktığım hakkında hiçbir fikrim yok.
JA Terroba

1
@gggg tembel temsili bir örnek gibi görünüyor , doğrulama
ASCII-yalnızca

1
@gggg İπsınırsız bir tıkaç kaynağı
H.PWiz

18

Excel, 212 bayt

=FIND(A1,"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196")

Excel yalnızca 15 ondalık basamağı tutar, böylece pi sadece sabit kodlanır. Bu, bu zorluk için oldukça zayıf bir üst sınır olmalıdır.


4
Kendi yazımla ilgili yorum yaptığım için üzgünüm, ancak seçmenlerden bazıları bana bu cevabı neden sevdiklerini söyleyebilir mi? Bir Excel formülünde olduğu gibi golf oynadı ama çok uzun ve hiç akıllıca değil.
Mühendis Tost,

6
Bunu sevdim çünkü pi'yi keyfi bir ondalık basamağa hesaplamak için yerleşik dilleri kullanan golf dillerine güvenmiyor. Yaratıcı olmayabilir, ancak pratiktir (pratikliğin burada önemi yoktur).
Scott

Sorusuna şöyle girdi veya cevap olduğunu belirtmez sahip kullanarak olabilir golf bu, taban 10 olmak CONCATve bir BBP formülü π-base16 ilk 200 hanesini hesaplamak yerine Onaltılık aramak için? (365 yok, bu yüzden test edemez)
Chronocidal

2
Office 365 only: kullanarak CONCAT, CODEve MIDben ila 143 202 karakterden (inc tırnak) den PI dize azaltılmış:CONCAT(CODE(MID(".ÜÁ£ÙÏ ¦®š«¦ Ï²œÔ“ÇŧÝËŠº”ᱬ»—‡ÑÀ†œ¾ˆãÖœƒ°™¢•‘†ÏÒŽÐÖ³ ÒžÂ¯‰¦¬¼ß²º–ŸÈµ»¨Ñœ°‹‘­‚ÔŠ›ÝÕ•Š·»À®–Þٶ݃Ñà",2*ROW(A1:A100)-1,2))-32)
Chronocidal

1
Office365 ile test ederken, girdi ne olursa olsun 14 çıktı veriyor gibi görünüyor?
Matthew Schlachter

9

Java 8, 615 217 202 184 182 166 165 bayt (hesaplanan 999 200 hane)

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 endeksli

Çevrimiçi deneyin.

Java'nın yerleşikliği Math.PI, diğer birçok dilde olduğu gibi 15 ondalık değer hassasiyetine sahiptir. Daha fazla haneye sahip olmak için, kendiniz BigIntegersveya ile kendiniz hesaplamanız gerekir BigDecimals. Bu, bunu yapmanın bir yoludur .. Belki birileri 211 byte, lol altında golf oynayabilir ..
EDIT: @primo'nun Python 2 cevabının limanı düzenlendi (onu yenmeyi unutma!) kodlanmış artık o kadar getirilmiş değil.Daha kısa olması için golf için sadece 7 bayt daha var.

@Neil sayesinde -15 bayt , aşağıdaki kodlanmış cevaptan daha kısa yapıyor! -Primo
sayesinde -36 bayt . -1 bayt değiştirmek için , çünkü daha 1 bayt kısadır (gerek aşık Yeni Java 10).
java.math.BigInteger t=null,T=t.TEN.pow(200),r=T;var T=java.math.BigInteger.TEN.pow(200);var r=T;varnull

Açıklama:

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 bayt (kodlanmış 200 hane)

"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196"::indexOf

0 endeksli

Çevrimiçi deneyin.


1
!p.equals(t.ONE)belki? Ayrıca, indexOf(n,1)-1bence eserler. Veya 2 bayt kaydedin ve 1 indeksli yapın.
Neil

İlkini nasıl özlediğimden emin değilim, ama ikincisi gerçekten hatırlamam gerekiyor. indexOfİlk mkarakterleri atlayan bir yöntem olduğunu bilmiyordum . TIL, teşekkürler!
Kevin Cruijssen


1
Ayrıca, pher defasında bir kez ( for(int p=667;p-->1;)) azalabilir ve sonra çarparak pbölün p-~p.
primo

1
Başlangıç ​​değeri rtam anlamıyla herhangi bir şey olabilir, ancak aşırı değerler daha fazla yineleme gerektirebilir. En iyi tohum (en az yineleme) aslında 4e200.
primo

6

05AB1E , 6 bayt

₁žs¦¹k

Çevrimiçi deneyin!

Nasıl?

₁        push 256
 žs      push pi to 256 places
   ¦     remove the leading 3
    ¹    push the input
     k   index inside that string

Benzer 6 baytlık çözümü aynı dilde alırsam, sizden sonra cevabımı silebilir miyim?
nicael

@nicael genellikle önemli değil, ancak çözümünüz 3yine de başarısız oluyor
Uriel

Oh, gerçekten, thnks
nicael

6

Matl , 16 15 bayt

YP8WY$4L)jXfX<q

Çevrimiçi deneyin!

açıklama

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

Çok güzel ve kısa! Nasıl çalıştığını açıklayabilir misiniz?
Rastgele çocuk

@ Therandomguy Tabii, açıklama eklendi
Luis Mendo

4

R + numaraları paketi, 52 bayt

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

Çevrimiçi deneyin!

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.


Maybe regexpr(scan(),numbers::dropletPi(200))-2?
djhurio

@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"?
Giuseppe

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

3
@djhurio right but regexpr(3,numbers::dropletPi(200))-2 returns -1 when it should return 9, try it
Giuseppe

3

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


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

Yes it would take a long time in raw form (it's still "using the Leibniz formula" I believe!)
Jonathan Allan

3

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

Nice! You don't need that space between -l and <<< though.
Sophia Lechner

You can convert to a program and use sed to save some bytes, Try it online!
Kritixi Lithos

@Cowsquack Wouldn't I need to include a shebang line in the byte count then?
cmaster

@cmaster shebang lines are not included in byte counts for any languages
Kritixi Lithos

@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.
cmaster

2

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.


Nice, you blow my attempts at encoding the data out of the water, your approach saves 38 bytes on the raw data.
Nit

+1 - I was about to post the exact same approach.
darrylyeo

Use x=>'50...'.replace(/.{9}/g,a=>parseInt(a,36)).search(x)+1 to save 10 bytes.
Neil

2

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!


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
Zac Faragher

Hyarus suggested using System;f=>"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196".IndexOf(f)+1; as an edit.
ovs

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

2

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!


My guess is that the Leibniz formula will be far shorter.
Jonathan Allan

@JonathanAllan Thanks! I will give it a try. I absolutely love this site! I've learned so much from you, guys! :)
Cristian Lupascu

@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!
Cristian Lupascu

1
You'd want to use the Euler transform (see my Jelly answer or primo's Python answer)
Jonathan Allan

1
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.
primo

2

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]

I guess you already know this, but you only need to output the first number in your sequence...
Timtech

Just thought I'd embrace the infinite-ness :D
tombop

2

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


If you post the complete code, it would make it easier to verify your answer.
primo

1
I can't post it because there are invalid characters that are removed/not displayed. I guess I can post the ascii codes though.
12Me21

You could post a hexdump, using xxd for example.
Nathaniel

2

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.


short AND readable!
pjs

2

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

fixed, 13 bytes. side note: this feels really cheaty :P
ASCII-only

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?
ASCII-only

@ASCII-only Fill weirdness - why does the cursor end up there?
Neil

:| oh i have no idea i should fix that asap
ASCII-only

nvm i'm an idiot, committed fix.
ASCII-only

2

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!


1
Clever idea! You can replace £X with ® and } with Ã
Oliver

@Oliver Thanks a lot for those, I'm still learning Japt so all help is very appreciated.
Nit

1
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 :)
Oliver

@Oliver Thanks for that, I simply tried the whole a-z range manually since it wasn't too much work. :P
Nit

1

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

My first attempt used sprintf to get the decimals. Using CONVFMT is definitely cleaner.
Robert Benson

2
No need to use the flag: meta consensus is to consider this a language distinct from AWK, "AWK with -M flag"
Giuseppe

Good to know. I guess I should spend more time on meta... with my loads of free time. :)
Robert Benson

1

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 × ( ... ))))


Is there a way to get digits from ØP in M?
dylnan

@dylnan Somewhat, but M is not Jelly.
user202729

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?
dylnan


1

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.


I tried to confirm the result but it doesn't seem to terminate (n=10**10**5 takes about 10s).
primo

@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 :)
DividedByZero

@primo I've changed the arbitrary precision library to bigfloat, it runs much quicker now.
DividedByZero

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

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!
primo

1

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 :)


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.
The random guy

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

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.
Dom Hastings

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!
Dom Hastings

Actually, it looks like the constant doesn't have 200 digits :( Try it online! - this should return 197.
Dom Hastings

0

Javascript 217 bytes (200 hardcoded)

a=>"14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196".search(a)+1

0

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;

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
primo

0

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!



0

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.


0

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.
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.