Смешайте пи и е, чтобы сделать пирог!


37

Все знают пи математическую константу, отношение длины окружности к ее диаметру.

3.14159265358979323846264338327950288419716939937510...

Вы , наверное , также знаете й математическую константу, основание натурального логарифма.

2.71828182845904523536028747135266249775724709369996...

Но ... ты знаешь пирог ? Это одна из самых важных констант (для меня). Это цифры Пи и Е чередуются.

32.1741185298216852385485997094352233854366206248373...

Как десятичное расширение:

3, 2, 1, 7, 4, 1, 1, 8, 5, 2, 9, 8, 2, 1, 6, 8, 5, 2...

Это последовательность OEIS A001355 .

КЛЮЧЕВОЕ СЛОВО: nonn, базовый, тупой , легкий

Это очень глупая последовательность.

Вызов

Напишите программу / функцию, которая принимает неотрицательное целое число n и выводит n-ю цифру круговой диаграммы .

Характеристики

  • Применяются стандартные правила ввода / вывода .
  • Стандартные лазейки будут запрещены .
  • Ваше решение должно работать как минимум с 50 цифрами каждой константы, что означает, что оно должно работать как минимум с 100 терминами последовательности (пожалуйста, постарайтесь не кодировать жестко: P).
  • Вывод для 2 или 3 не является десятичной точкой .
  • Ваше решение может быть либо 0-индексированным, либо 1-индексированным, но укажите, какое именно.
  • Эта задача заключается не в том, чтобы найти кратчайший подход на всех языках, а в том, чтобы найти кратчайший подход на каждом языке .
  • Ваш код будет оцениваться в байтах , обычно в кодировке UTF-8, если не указано иное.
  • Встроенные функции, которые вычисляют эту последовательность: Разрешены но приветствуется решение, которое не зависит от встроенного.
  • Пояснения, даже для «практических» языков, приветствуются .

Контрольные примеры

Это 0-индексированные.

Input   Output

1       2
2       1
11      8
14      6
21      4
24      9
31      5

В нескольких лучших форматах:

1 2 11 14 21 24 31
1, 2, 11, 14, 21, 24, 31

2 3 12 15 22 25 32
2, 3, 12, 15, 22, 25, 32

8
Согласно OEIS, ключевое слово dumbпросто означает неинтересный без каких-либо особых свойств.
Okx

1
@ Downvoter Может быть, есть какая-то причина?
полностью человек

27
Можно утверждать, что результат peiне такpie
Заид

1
Я не делал
отрицательное

1
В 13:59, @txtechhelp? ;)
WallyWest

Ответы:


12

Mathematica, 50 bytes

1-indexed

(Riffle@@(#&@@RealDigits[#,10,5!]&/@{Pi,E}))[[#]]& 

Can you explain how this works?
Stevoisiak

it's easy. It takes 120(5!) elements of each and riffle them
J42161217

Nice! I tried to beat your solution by avoiding Riffle, but my solution comes up one byte short: RealDigits[If[OddQ@#,Pi,E],10,#][[1,Ceiling[#/2]]]&
Mark S.

This appears not to work. It returns a single digit.
DavidC

@DavidC Yes!.."outputs the nth digit of pie" Exactly! why did you downvote???
J42161217

9

Haskell, 154 147 146 bytes, NO HARDCODING OR USE OF BUILTIN CONSTANTS

This solution calculates e and pi using infinite series and stores them in arbitrary-precision fixed-point integers (Haskell's built-in Integer type and its Rational extension).

import Data.Ratio
s n=product[n,n-2..1]
r=[0..164]
f n=(show$round$(*10^50)$sum[[2*s(2*k)%(2^k*s(2*k+1)),1%product[1..k]]!!mod n 2|k<-r])!!div n 2

Ungolfed:

import Data.Ratio

semifact :: Integer -> Integer
semifact n = product [n, n-2..1]

pi_term :: Integer -> Rational
pi_term i = semifact (2*i) % (2^i * semifact (2*i+1))

--requires 164 terms to achieve desired precision
pi_sum :: Rational
pi_sum = 2 * (sum $ map (pi_term) [0..164])

--requires 40 terms to achieve desired precision
e_sum :: Rational
e_sum = sum [1 % product [1..k] | k<-[0..40]]

-- 51 digits are required because the last one suffers from rounding errors 
fifty1Digits :: Rational -> String
fifty1Digits x = show $ round $ x * 10^50

pi51 = fifty1Digits pi_sum
e51  = fifty1Digits e_sum

-- select a string to draw from, and select a character from it
pie_digit n = ([pi51, e51] !! (n `mod` 2)) !! (n `div` 2)

0-indexed. Accurate for input 0-99, inaccurate for input 100-101, out-of-bounds otherwise.

Explanation:

Calculates pi using this infinite series. Calculates e using the classical inverse factorial series. Theoretically these aren't the ideal formulas to use, as they aren't very terse in terms of bytecount, but they were the only ones I could find that converged quickly enough to make verification of accuracy feasible (other sums required hundreds of thousands if not millions of terms). In the golfed version, e is calculated to a much higher precision than necessary in order to minimize bytecount. Both constants are calculated to slightly more digits than necessary to avoid rounding errors (which are responsible for the awkward tail of incorrect values).

The constants are calculated as arbitrary precision integer ratios (Rational), then multiplied by 10^50 so that all necessary digits remain intact when the ratio is converted to an (arbitrary precision) integer (Integer). This also avoids the issue of avoiding the decimal point in the numbers' string representations, which the function alternatively draws characters from.


8

Taxi, 749 bytes

'3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919' is waiting at Writer's Depot.Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to The Underground.Go to Writer's Depot:n 1 l 1 l 2 l.Pickup a passenger going to Chop Suey.Go to Chop Suey:n 3 r 3 r.[a]Pickup a passenger going to Narrow Path Park.Go to The Underground:s 1 r 1 l.Switch to plan "b" if no one is waiting.Pickup a passenger going to The Underground.Go to Narrow Path Park:n 4 l.Go to Chop Suey:e 1 r 1 l 1 r.Switch to plan "a".[b]Go to Narrow Path Park:n 4 l.Pickup a passenger going to Post Office.Go to Post Office:e 1 r 4 r 1 l.

Try it online!

Trying to compute pi or e programmatically in Taxi would be a nightmare, although I'm sure it can be done. Thus, it's far shorter to just hardcode the first 100 digits in the sequence. It feels pretty cheap but it's definitely the shortest Taxi code that meets the challenge.

It hard-codes the sequence as strings, takes in n, then iterates n down and removes the first character in the string each time. When n=0, output the first character. This is one-indexed.

Un-golfed / formatted:

'3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919' is waiting at Writer's Depot.
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to The Underground.
Go to Writer's Depot: north 1st left 1st left 2nd left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 3rd right 3rd right.
[a]
Pickup a passenger going to Narrow Path Park.
Go to The Underground: south 1st right 1st left.
Switch to plan "b" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up: south.
Go to Narrow Path Park: north 4th left.
Go to Chop Suey: east 1st right 1st left 1st right.
Switch to plan "a".
[b]
Go to Narrow Path Park: north 4th left.
Pickup a passenger going to Post Office.
Go to Post Office: east 1st right 4th right 1st left.

6

Python 2, 88 bytes

-4 bytes thanks to the base conversion idea of @EriktheOutgolfer.

lambda n:`int("SVBPXJDZK00YCG3W7CZRA378H4AM5553D52T52ZKAFJ17F4V1Q7PU7O4WV9ZXEKV",36)`[n]

Try it online!

Python 2 + sympy, 92 bytes

0-indexed. Thanks to Rod for reminding me to switch to from sympy import*, which I formerly forgot.

lambda n:sum([('3','2')]+zip(`N(pi,50)`,`N(E,50)`[:47]+'6996')[2:],())[n]
from sympy import*

Try it online!

Python 2, 114 bytes

I honestly think the shortest solution is hardcoding, since Python doesn't have useful built-ins.

lambda n:"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"[n]

Try it online!

Python 2, 114 bytes

Equivalent solution by @totallyhuman.

'3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919'.__getitem__

Try it online!


Before downvoting, take your time to search for a shorter solution.
Mr. Xcoder


@totallyhuman Thanks
Mr. Xcoder

8
The equivalent solution that you edited in is actually equivalent code, not equivalent byte count. :P
totallyhuman

1
@totallyhuman Lol I saw your comment and understood it but I completely forgot to fix, because I was laughing about my own mistake. Thanks for editing in!
Mr. Xcoder

5

05AB1E, 10 bytes

žsтžtøJþsè

Explanation:

žs          Get the first input digits of pi
  тžt       Get 100 digits of e
     ø      Zip them together
      J     Join into a string
       þ    Remove non-digits
        sè  0-indexed index of input in the resulting list

0-indexed.

Try it online!


1
Too many 05AB1Es... :P
Mr. Xcoder

@Mr.Xcoder Well, 05AB1E is the language with the pi and e builtin...
Okx

@Mr.Xcoder There are builtins that's why.
Erik the Outgolfer

@totallyhuman no it doesn't.
Erik the Outgolfer

@Dorian Your version doesn't work. You're using the legacy version, but žt wasn't an infinite list back then, which is why Okx is using the first 100 digits of e in his program. Changing it to the new version of 05AB1E (where both pi and e are an infinite list) still wouldn't work in your current version, because the zip would create pairs and the Join would join those pairs instead of everything. 9 bytes are still possible by replacing J with S in the new version however, where S makes it a flattened list of chars/digits
Kevin Cruijssen

5

Python 3, 83 80 bytes

0-indexed.

lambda n:('%d'*51%(*b' )4bD4&6UcF^#!U+B>0%"WK\<>0^GO9~1c]$O;',))[n]

Try it online!

There are some non-printable characters in there that can't be seen properly in a browser.

This works by building the tuple (32, 17, 41, 18, 52, ...) from the ASCII codes of the characters in the hardcoded bytestring. The tuple is converted to the string '3217411852...', from which we select the right digit.


4

Polyglot, 108 bytes

n=>"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"[n]

Works in:

  • C#
  • JavaScript

I think this is the shortest you can do in C# seeing as it is 252 bytes to find the Nth decimal of pi.


JS polyglot :-)
Arnauld

@Arnauld Updated :)
TheLethalCoder

7
This isn't a Java Polyglot! You can't index into Non-Array Objects in Java.
Roman Gräf

1
This technically works but I downvoted because it's a) not very competitive and b) extremely boring and trivial.
HyperNeutrino

4
@HyperNeutrino It's C# and JavaScript when are they ever competitive? And boring and trivial maybe but would you rather I did a 500 byte answer in C# that was clever? No because that conflicts with point 1. This is as short as it gets...
TheLethalCoder

4

Java 8, 420 417 413 404 380 358 (calculated) & 115 110 (hardcoded) bytes

Calculated (420 417 413 404 380 358):

import java.math.*;n->{int i=1,x=99;BigDecimal e,f=e=BigDecimal.ONE;BigInteger p,a=BigInteger.TEN.pow(x);for(p=a=a.add(a);i<x;)e=e.add(e.ONE.divide(f=f.multiply(f.valueOf(i++)),new MathContext(x,RoundingMode.HALF_UP)));for(i=1;a.compareTo(a.ZERO)>0;)p=p.add(a=a.multiply(a.valueOf(i)).divide(a.valueOf(i+++i)));return n==1?50:((n%2<1?p:e)+"").charAt(-~n/2);}

Try it here.
Prove it outputs correct result for required 100 items.

Hardcoded: (115 110 bytes):

"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"::charAt

Try it online.

0-indexed

-9 and -5 bytes thanks to @Nevay.
-24 bytes thanks to @ceilingcat.

  • Your solution must work for at least 50 digits of each constant which means it should work for at least a 100 terms of the sequence (please, try not to hardcode :P)
  • Built-in functions that compute this sequence are allowed but including a solution that doesn't rely on a built-in is encouraged

You've asked for it.. ;)

Java's built-in Math.PI and Math.E are doubles, which have a max precision of just 16. Therefore, we'll have to calculate both values ourselves using java.math.BigInteger and/or java.math.BigDecimal.
Since I've already calculate PI before in another challenge, I've used that same code using BigInteger. The algorithm for Euler's number uses BigDecimal however.
The resulting p and e are therefore: 31415... and 2.718....

Could probably golf it by only using BigDecimal, but was giving some incorrect answers for PI, so I now use both BigDecimal and BigInteger.

Explanation:

import java.math.*;           // Required import for BigDecimal and BigInteger
n->{                          // Method with integer as parameter and char as return-type
  int i=1,                    //  Start index-integer at 1
      x=99;                   //  Large integer we use three times
  BigDecimal e,               //  Euler's number
             f=e=BigDecimal.ONE;
                              //  Temp BigDecimal (both `e` and `f` start at 1)
  BigInteger p,               //  PI
             a=BigInteger.TEN.pow(x);for(p=a=a.add(a);
                              //  Temp BigInteger (where both `p` and `a` starts at 10^99*2)

       i<x;)                  //  Loop (1) 99 times (the higher the better precision)
    e=e.add(                  //   Add the following to `e`:
       e.ONE.divide(f=f.multiply(f.valueOf(i++)),
                              //    First change `f` by multiplying it with `i`
        new MathContext(x,RoundingMode.HALF_UP))))
                              //    And then add 1/`f` to `e`
                              //    (RoundingMode is mandatory for BigDecimal divide)
  for(i=1;                    //  Reset `i` back to 1
      a.compareTo(a.ZERO)>0;) //  Loop (2) as long as `a` is not 0
    p=p.add(                  //   Add the following to `p`:
       a=a.multiply(a.valueOf(i))
                              //    First change `a` by multiplying it with `i`,
          .divide(a.valueOf(i+++i)));
                              //    and dividing it by `2*i+1`
                              //    And then add this new `a` to `p`
  // We now have `p`=31415... and `e`=2.718...
  return n==1?                // If the input (`n`) is 1:
          50                  //  Return 2
         :                    // Else:
          ((n%2<1?            //  If `n` is divisible by 2:
             p                //   Use `p`
            :                 //  Else:
             e)               //   Use `e` instead
    +"")                      //  Convert BigDecimal/BigInteger to String:
        .charAt(-~n/2);}      //  And return the `(n+1)//2`'th character in this string

Not sure if it will help you but my C# algorithm for calculating pi came in at 8 bytes shorter than your Java version.
TheLethalCoder

Note though to get it to work properly for this question change (d+=2) to ++d and return p%10+1 to just return p%10.
TheLethalCoder

@TheLethalCoder Feel free to make a C# answer for this challenge. :) Although you'll also have to calculate Euler's number. My answer is kinda for lolz anyway, since hardcoding the output is shorter anyway..
Kevin Cruijssen

1
You've asked for it.. ;) Hey, I like your first one better. I got way more hardcoded answers than I expected...
totallyhuman

1
You can save 9 bytes in your calculated answer by using charAt(n+1>>1) and 5 bytes in your hardcoded version by using a method reference "..."::charAt.
Nevay

3

Seed, 6015 bytes

105 41100973201674650461227976639700390615120600528953176107701316721890649738810349651490948904154731057172335535600875054878204557287393379815378680878571406244365932330202793040308312687924242319799562985464135998860369933720376853281630432469462831217924775601393232895404104191613314969008627719099002734936685651970933027922574843126481552407811220371545812798263882325951724505132794956253992779856191832909434513683936955184871247159313261417328850445886987045814618325821125417040265540589403338721758954467831926977078444612065747526326682314711350486782090838673475876960125016098416460032667015813053483457246043486676622061645094043655351781242050448580132075920324099742699960838361839038297355120817832056960516761862493176616153258281345538652844974811030063414112136642097000574165433957710342430709643110444042577685157477268110199017600011209827070311299268347100419887111107237908884608557593677163764286026624394674781868689858494991328505977301270068505397030743037416430245399054325956185200430657008806539374392625804513081295070438243600044274289109395357299275275193717501822777898664715885427884193864182834402097958423697356485767670945673525604620701482288023981110598866625872386643941558021439168402392304238271452444124214301243311025121833097491087918320170873313832323794851508364788578530614246140801266858481189449278157296335592848066512127882306035576754122325822200069362884409931190620435627809384380203617488253034370361172908245852012086081807945576657014184275798330804532115103840313004678040210379846666674881048346897213048386522262581473085489039138251061251160730845385869281787222083186331344552658814775998639661361866503862291670619153718574270905089351133527806484519543645501497150560454761284099358123613642350160410944676702481576280832672884549762767667090615809061739499629798396737503512011645776394176807352443544839957773371384141101627375926404212619777658374366513665083032140398814384622434755543347503025479743718569310129255927244046638238401670388409731849963600790867434678993019370132638962549859363736476668247251402420832876258626149639101811361047924632565285870213656416957893835899254928237592711662454838295046528789720146967061486405916116778722736283489123195985053535189375957277052428901645131462087039117212488839670735246752589931585405440449333046667938628384693216121067951290025349082277568986632815062532963505690244579740140120806885104683071514922412748240497612209609661707922754236180441892543545377867355182682381812487973645406703590150722720330526173957597156314579144484166520730013480681064941752984345205140917291104888971742824066713606933406657345121342075268990055328274845008936364502884461548416337689565392911129757761902576946104722487260155373897552821908338346641549478063474748830482136404008215583192489320750526753663943267086203954602839906762640389978523894333743126288529975769945319614142422443068420170103245659109689433597701350198280212250954698442638475209618790055335813263132865176791663235801963797561493995544185124734214257034901773781134331460320221759556924556747571745834582344275416625351302153332814233497096345055392255809024712740720006219615340819493781244665414077298346378966540544979367367978334759985048507214749726072645238624803791884339024844989975370042133733339339038567691571361407296615851372112592532463329778465699812822089846474961581380707849259093905314170108054540333209088059730272087864344697983074458088984533095183089310714804468718319244214535941276969904638763288063417624586766891798378622613765728303031397998644194508610598078718347204813844240434145846888722334194516524032354042557957058092854659539699310565707914118281251563405735083553254856313838760124953245573676126601070861004186509621892263623745673900572829301771299438501543213489182375655869072568437776298051260531944785904157204006430131566234389896821642210616326951771496269255716808352415001187083781128619236455170025989777631182990311607133740812107138446626302353752098982590371714623080450836912706275397973009559314275978915463843159370230629290376520494894845680706499809017211545204670148071902560908658269183779180493590025891585269507219866461550160579656755846447951259951641828495549544791046179035585611272240116822105364823082512055639047431280117805724371019657801828634946412396263504315569042536942671358095826696817513115447079645898107923447321583282886740680340887700198072304400536529418546232473450984945589794448490331085275232352881571706521961358975744067916422124670374397682877259664913100427726059898474024964867713698696116581478101206003313106174761699804016604950094008714907179862448792216891309734208815522069346791369498202430302292199779590583788518283934542807403049256936179914953814019565550264909025345322516061595136601312434888871667940394250767164496543418483237896796108764367721411969986710930448108645039275082356457263454340220118278471652962484104099512207532103709146426640958406853240342441810465024550617909657901698718289260589269758398513490424434162831332785821428006396653475356712733072469052427934231406388810607688824035522285626563562286337967271308076321307276537761026788485320280603487776428017017298356181654076403306265118978333909378403193559129146468182910851996415072056976175613473847242292911071040966109905552914332596680497156169349277079292398091020434667210493868422848588893205157133171899819212153010393580099455957808703428739456223073813663954919146593698106305501988107196273527346690785289909397140611634970017071011599022429384594426022933102487171920965595473754661194965266230932928905708783854897164127767575976566931916632077914904360565095752466049885656187054491320449776951484812738806536727562344348761718424255018794271994537719709226236497935053971406685810778014002594041715040546776952342303797267458880802314841325359844565479173256964507237937290466116935912176054052746039378370966040054779443633371806403649852746347690237831260027483859907620684197542069045517397230169577918374265220969534695931904

The Seed equivalent to my Befunge answer. Like I mentioned there, the Befunge program this outputs does not work on TIO because TIO seems to have internal line wrapping at 80 characters.


How? Just... how?
NieDzejkob


3

Excel, 113 bytes

1-indexed

=MID("3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919",A1,1)

PI() is only accurate up to 15 digits. Similar for EXP(1).

60 42 byte solution that works for Input <=30 (-18 bytes thanks to @Adam)

=MID(IF(ISODD(A1),PI(),EXP(1)/10)/10,A1/2+3,1)

The basic concept in your second approach can be shortened to 46 bytes by only having the pi/e choice inside the if(...) statement: =MID(IF(ISODD(b1),PI(),EXP(1)/10)/10,b1/2+3,1) .Can't get around the imprecision of pi() and exp(), though
Adam

2

05AB1E, 13 bytes

Éi<;žtë;žs}þθ

Try it online!

Similar to Magic's answer, but kinda different.

Explanation:

Éi<;žtë;žs}þθ Supports 9842 digits of e and 98411 digits of π
É             a % 2
 i    ë   }   if a==1
  <            a - 1
   ;           a / 2
    žt         e to a digits
              else
       ;       a / 2
        žs     π to a digits
           þ  keep chars in [0-9] in a
            θ a[-1]


2

Japt, 55 bytes

" ®v4bØUî6UcF^#ß&6$Îø%\"Wí;<>0^GO9G1c]$O;"cs gU

Test it online! Contains a few unprintables.

Works by replacing each character in the string with its charcode, then returning the digit at the correct index. The string was generated by this program:

r"..(?=[^0]0)|25[0-5]|2[0-4].|1..|.(?=[^0]0)|..|."_n d

Test it online!


2

Julia, 63 bytes

1-indexed

a(n)=replace(string(BigFloat(n%2>0?π:e)),'.',"")[ceil(Int,n/2)]

Converts pi or e to a string, removes the decimal place, and then calls the appropriate digit. Returns a character representation of the digit.


1
Welcome to PPCG!
Martin Ender

2

Seed, 5852 5794

Based on TehPers Befunge answer.

105 113002164871590739314987829049307960037656198834866427236905121954115803425132377811017261267508985918460516699110604069383390959259813211529503372875273808710588124346256307646667819637622583266174711430236542978713371651111138161258814014430791036278292414499656452941169156830257154682891945427168323349789659414918954432721496930284898425790960909241894284781315857049329769224542864680353681534575933422424767707487267105729647869707615701969946632447899025935146610872657847217500147458582162977840688029783675330301220720997622926460983429318136766448664249339408547350925381367609377956773869746595751981270619213926147211890869963881664082555405185043676206172128177189246682247058574292315899935090905437591661266740559405162222996969611028558290091641009922497490272073602109698144136237139892288758564286335997806260176733841267995620802629495311018527105600614517192092649739617993355354764787635487444533658359428565687080154517757890270592773372024921163684788486949109705417597693762970920021249476121718487310885214065572289535961346215683364612315264822079329585462764945219095679916070353286147709600972570614120233113128790126662286156057686903720942137873912511576516301011227356138489027470697247933585954842450741358944012216071769761815733661875419652839052931663415505744712631746787832014322014868591150702573172166945669229230913363344728435313054200429998131904807363769656763488962394934163037250505543518966376704416506376321611183458869639917973770286152983694797090148271251013631504215211063321591324191669491956643311240521006341404267009756225607360091610388650359124819175883509292439414777620417167522685091490259040136036034579692518124798164708926188495203908126898658681865909050531795557967108988591574556866175888346903123079427257115921330028144573070329426929531076740133942295248077792078687841078079268719526879909788542680179524275827358784127273168527872136974672731344708599614215281119934065639520745234349293757970245111171645337101665479132283486591886003364231440299524048129365242579269735889557760669994751103041672868435202250671067797684169074938720299249334705611438978473321117244865600759558291122236484729311642571499634395815652244856036306309426007390684666411239172295850545146441402560560341332328380709310752195557971123590340315335700317013293851268994688275799911771016064582194514876381367454879798122437554725457606331047947374904420197286393544275845842428580614721866647174706186991857454507274563175804998237200744486630048509506143395191487837350195267021654643538881849734231141725424601330485671509495305148131743810493387517147034390010671970517110205867361059474884617856208037099248888176490940290206562546475055852738977573593904440085870522989324367348662198800983879197171460362503731088514814079681375712029106737219687292822832109515671205430310190195987438406367288649547279607011336560384368751332286717619791748985553772693409536049147249735256714714024639568250305940497144973962564739882059896415826530266878391650198495604496902130260192048771738287910630368379535990532534781447331851939134456545892027046327917478474665636031407046424166662224021038524518495928222266639887065627494062967545357424609779938336142901480061872078034629454218589211641784224052477683545808790001800789690114038324361179370588354779145068239226196064382427132818933211646651925556744151561592584028445615402230429197821863456537957514864271133762278972184204869644394521345416271355631691230134619361522785486931887108980824977655507783434249228188856167617108716815094123730600710952108190016969333162591813869968264515792463284254698981261829244948079958090972029228009509584596285072135655480768099128872214767174088557681133949254945492690159492733827441038586327672595878146092413446635826008953390852510674046712247097336867698827720756888212247984007467030021498051100766545723521829074239408920419228250849112577718015149186696163811124496295326839833968618977237298392606857935004740275480306823203459402487279114142809512031125908797313635314972863814303513678473099927026607274900456721755543827098812499754976223002068988166928549986537496305328253011857088410803897580533534109872057730526662956704744519240370047288779478242394065841217642437006215862683465340567540141567908382219161706192517414918920335949928316037480173726078040746055914732675899449554957974703336123447175047024451331108027464919186072451108622235369696655603590410141636686651842707160470522293863594778186952018113745140884964015958604111363959827254006218576819095970777536217638180423889634131748541027983145892759706009491393182243795048903475541887656616509860914555116317017006096855080419242968307668243354850411304416190687499212061972410926839498652918205097786610428363995506942432312411823427047186868840577006626729855054434535548056834448216246518404910539196129433524592691043628016754842890872507304906318742343175154206452151706945249818234640798419739099879992464416047867973147679669193814805760372826774933145903193782399649588923478706079107924185454258124307881293104633301338073776691416142537130145576268465288334517657616632085092685517319761353655436962877242874726395604578641629542918465198557048233824201655936372542110027024362703019743929091896294865287339787424383206745979183701439427840308590723461600323162160013212640322512322745821468600689724015806074498945821524378781714871793675698107420867876597774494057787557965469877984960511884501039590623229374018088813765629152405059007172424233594237883453270762239632440547727976805269692785605606401953257035710157327757004025470677546239616027587603888642814609779889799831508662735822095183804904610021893861075323086016909910447437995018169256183487254051119590377469311351028312018776850026116029689211988391328901764154505776555092490963288792

Nice job! I'm a bit curious about how you golfed it.
TehPers

2

Malbolge Unshackled (20-trit rotation variant), 3,64E6 bytes

Size of this answer exceeds maximum postable program size (eh), so the code is located in my GitHub repository (note: Don't copy the code using CTRL+A and CTRL+C, just rightclick and click "Save destination element as...").

How to run this?

This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations).

The best one I could find is the fixed 20-trit rotation width variant, that performs very well, calculating (pretty much) instantly.

To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter.

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
        "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";

typedef struct Word {
    unsigned int area;
    unsigned int high;
    unsigned int low;
} Word;

void word2string(Word w, char* s, int min_length) {
    if (!s) return;
    if (min_length < 1) min_length = 1;
    if (min_length > 20) min_length = 20;
    s[0] = (w.area%3) + '0';
    s[1] = 't';
    char tmp[20];
    int i;
    for (i=0;i<10;i++) {
        tmp[19-i] = (w.low % 3) + '0';
        w.low /= 3;
    }
    for (i=0;i<10;i++) {
        tmp[9-i] = (w.high % 3) + '0';
        w.high /= 3;
    }
    i = 0;
    while (tmp[i] == s[0] && i < 20 - min_length) i++;
    int j = 2;
    while (i < 20) {
        s[j] = tmp[i];
        i++;
        j++;
    }
    s[j] = 0;
}

unsigned int crazy_low(unsigned int a, unsigned int d){
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    int position = 0;
    unsigned int output = 0;
    while (position < 10){
        unsigned int i = a%3;
        unsigned int j = d%3;
        unsigned int out = crz[i+3*j];
        unsigned int multiple = 1;
        int k;
        for (k=0;k<position;k++)
            multiple *= 3;
        output += multiple*out;
        a /= 3;
        d /= 3;
        position++;
    }
    return output;
}

Word zero() {
    Word result = {0, 0, 0};
    return result;
}

Word increment(Word d) {
    d.low++;
    if (d.low >= 59049) {
        d.low = 0;
        d.high++;
        if (d.high >= 59049) {
            fprintf(stderr,"error: overflow\n");
            exit(1);
        }
    }
    return d;
}

Word decrement(Word d) {
    if (d.low == 0) {
        d.low = 59048;
        d.high--;
    }else{
        d.low--;
    }
    return d;
}

Word crazy(Word a, Word d){
    Word output;
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    output.area = crz[a.area+3*d.area];
    output.high = crazy_low(a.high, d.high);
    output.low = crazy_low(a.low, d.low);
    return output;
}

Word rotate_r(Word d){
    unsigned int carry_h = d.high%3;
    unsigned int carry_l = d.low%3;
    d.high = 19683 * carry_l + d.high / 3;
    d.low = 19683 * carry_h + d.low / 3;
    return d;
}

// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
    if ((mem[d.area])[d.high]) {
        return &(((mem[d.area])[d.high])[d.low]);
    }
    (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
    if (!(mem[d.area])[d.high]) {
        fprintf(stderr,"error: out of memory.\n");
        exit(1);
    }
    if (last_initialized) {
        Word repitition[6];
        repitition[(last_initialized-1) % 6] =
                ((mem[0])[(last_initialized-1) / 59049])
                    [(last_initialized-1) % 59049];
        repitition[(last_initialized) % 6] =
                ((mem[0])[last_initialized / 59049])
                    [last_initialized % 59049];
        unsigned int i;
        for (i=0;i<6;i++) {
            repitition[(last_initialized+1+i) % 6] =
                    crazy(repitition[(last_initialized+i) % 6],
                        repitition[(last_initialized-1+i) % 6]);
        }
        unsigned int offset = (59049*d.high) % 6;
        i = 0;
        while (1){
            ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
            if (i == 59048) {
                break;
            }
            i++;
        }
    }
    return &(((mem[d.area])[d.high])[d.low]);
}

unsigned int get_instruction(Word** mem[], Word c,
        unsigned int last_initialized,
        int ignore_invalid) {
    Word* instr = ptr_to(mem, c, last_initialized);
    unsigned int instruction = instr->low;
    instruction = (instruction+c.low + 59049 * c.high
            + (c.area==1?52:(c.area==2?10:0)))%94;
    return instruction;
}

int main(int argc, char* argv[]) {
    Word** memory[3];
    int i,j;
    for (i=0; i<3; i++) {
        memory[i] = (Word**)malloc(59049 * sizeof(Word*));
        if (!memory) {
            fprintf(stderr,"not enough memory.\n");
            return 1;
        }
        for (j=0; j<59049; j++) {
            (memory[i])[j] = 0;
        }
    }
    Word a, c, d;
    unsigned int result;
    FILE* file;
    if (argc < 2) {
        // read program code from STDIN
        file = stdin;
    }else{
        file = fopen(argv[1],"rb");
    }
    if (file == NULL) {
        fprintf(stderr, "File not found: %s\n",argv[1]);
        return 1;
    }
    a = zero();
    c = zero();
    d = zero();
    result = 0;
    while (!feof(file)){
        unsigned int instr;
        Word* cell = ptr_to(memory, d, 0);
        (*cell) = zero();
        result = fread(&cell->low,1,1,file);
        if (result > 1)
            return 1;
        if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
            break;
        instr = (cell->low + d.low + 59049*d.high)%94;
        if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
                || cell->low == '\n');
        else if (cell->low >= 33 && cell->low < 127 &&
                (instr == 4 || instr == 5 || instr == 23 || instr == 39
                    || instr == 40 || instr == 62 || instr == 68
                    || instr == 81)) {
            d = increment(d);
        }
    }
    if (file != stdin) {
        fclose(file);
    }
    unsigned int last_initialized = 0;
    while (1){
        *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
                *ptr_to(memory, decrement(decrement(d)), 0));
        last_initialized = d.low + 59049*d.high;
        if (d.low == 59048) {
            break;
        }
        d = increment(d);
    }
    d = zero();

    unsigned int step = 0;
    while (1) {
        unsigned int instruction = get_instruction(memory, c,
                last_initialized, 0);
        step++;
        switch (instruction){
            case 4:
                c = *ptr_to(memory,d,last_initialized);
                break;
            case 5:
                if (!a.area) {
                    printf("%c",(char)(a.low + 59049*a.high));
                }else if (a.area == 2 && a.low == 59047
                        && a.high == 59048) {
                    printf("\n");
                }
                break;
            case 23:
                a = zero();
                a.low = getchar();
                if (a.low == EOF) {
                    a.low = 59048;
                    a.high = 59048;
                    a.area = 2;
                }else if (a.low == '\n'){
                    a.low = 59047;
                    a.high = 59048;
                    a.area = 2;
                }
                break;
            case 39:
                a = (*ptr_to(memory,d,last_initialized)
                        = rotate_r(*ptr_to(memory,d,last_initialized)));
                break;
            case 40:
                d = *ptr_to(memory,d,last_initialized);
                break;
            case 62:
                a = (*ptr_to(memory,d,last_initialized)
                        = crazy(a, *ptr_to(memory,d,last_initialized)));
                break;
            case 81:
                return 0;
            case 68:
            default:
                break;
        }

        Word* mem_c = ptr_to(memory, c, last_initialized);
        mem_c->low = translation[mem_c->low - 33];

        c = increment(c);
        d = increment(d);
    }
    return 0;
}

This looks like more than 3646 bytes
H.PWiz

@H.PWiz forgot the E, sorry
Krzysztof Szewczyk

1

05AB1E, 14 bytes

žssžt‚øJ'.Ks<è

Try it online!


This answer is 0-indexed.

žs              # pi to N digits.
  sžt           # e to N digits.
     ‚øJ        # Interleave.
        '.K     # No decimal points.
           s<è  # 0-indexed digit from string.

I know there are already three other 05AB1E answers, so it doesn't really matter, but you can golf 3 bytes by changing '.K to þ and remove the <. (Not sure why you even included the <, since you state your answer is 0-indexed. Your current answer is 1-indexed with the <.)
Kevin Cruijssen

Hmm.. you can also remove the , since the zip does this implicitly, but I see it's than almost exactly the same as the other 10-byte answer..
Kevin Cruijssen

1

Python 3 + SymPy, 109 Bytes

0-indexed Try it online!

from mpmath import*
mp.dps=51
print(''.join(['32']+[str(pi)[i]+str(e)[i]for i in range(2,51)])[int(input())])

Beat hardcoding by 5 bytes!! But could probably be better. But beating hardcoding makes me feel good :)


1

Pyth, 35 bytes

@.i`u+/*GHhyHyK^T99rJ^2T0Z`sm/K.!dJ

Test suite

Since Pyth doesn't have built-in arbitrary precision pi and e constants, I calculate them directly.

Calculating pi:

u+/*GHhyHyK^T99rJ^2T0

This uses the following recurrence continued fraction to compute pi: 2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + ...)))). I got it from another PPCG answer. It is derived in equations 23-25 here.

I calculate it from the inside out, ommitting all terms beyond the 1024th, since the later terms have little effect on the number, and I maintain 99 digits of precision to make sure the first 50 are correct.

Calculating e:

sm/K.!dJ

I sum the reciprocals of the first 1024 numbers, to 99 digits of precision.

Then, I convert both numbers to strings, interlace them, and index.


1

MATLAB, 93 Bytes

n=input('');
e=num2str(exp(1));
p=num2str(pi);
c=[];
for i=1:length(p)
 c=[c p(i) e(i)];
end;
c(n)

A simple explanation is that this first converts e and pi to strings, then goes through a for loop concatenating the digits. Here, c is pie, p is pi, and e is e.

I have also broken this up into several lines for readability, but the actual code is all on one line with minimal spacing.


Welcome to the site!
DJMcMayhem

Thanks, I've been browsing Code Golf for quite a while, and finally decided to give it a go myself.
a13a22

This has some issues, mainly that it appears to take no input. You need to modify your function so that given the integer, n, it will produce the nth digit of the Pie sequence. You can also reduce your bytecount by reducing your variable names to a single char
Taylor Scott

Sorry, I fixed the variable names for byte count. As for the nth digit, am I just supposed to define n=?, or am I supposed to take a user input?
a13a22

Looks like you already figured it out, but you should prompt the user for input, however, it is not necessary to have any formatting attached to that prompt, so you an use input('') in place of input('n')
Taylor Scott

1

C# + BigDecimal, 377 372 bytes

d=>{if(d%2<1){d/=2;int l=++d*10/3+2,j=0,i=0;long[]x=new long[l],r=new long[l];for(;j<l;)x[j++]=20;long c,n,e,p=0;for(;i<d;++i){for(j=0,c=0;j<l;c=x[j++]/e*n){n=l-j-1;e=n*2+1;r[j]=(x[j]+=c)%e;}p=x[--l]/10;r[l]=x[l++]%10;for(j=0;j<l;)x[j]=r[j++]*10;}return p%10;}else{CognitioConsulting.Numerics.BigDecimal r=1,n=1,i=1;for(;i<99;)r+=n/=i++;return(r+"").Remove(1,1)[d/2]-48;}}

Saved 5 bytes thanks to @Kevin Cruijssen.

No TIO link because of the external library, unfortunately C# doesn't have a built in BigDecimal class so this external one will have to do. Probably some golfing still possible but no time right now.

Full/Formatted Version:

namespace System.Linq
{
    class P
    {
        static void Main()
        {
            Func<int, long> f = d =>
            {
                if (d % 2 < 1)
                {
                    d /= 2;

                    int l = ++d * 10 / 3 + 2, j = 0, i = 0;
                    long[] x = new long[l], r = new long[l];

                    for (; j < l;)
                        x[j++] = 20;

                    long c, n, e, p = 0;

                    for (; i < d; ++i)
                    {
                        for (j = 0, c = 0; j < l; c = x[j++] / e * n)
                        {
                            n = l - j - 1;
                            e = n * 2 + 1;
                            r[j] = (x[j] += c) % e;
                        }

                        p = x[--l] / 10;
                        r[l] = x[l++] % 10;

                        for (j = 0; j < l;)
                            x[j] = r[j++] * 10;
                    }

                    return p % 10;
                }
                else
                {
                    CognitioConsulting.Numerics.BigDecimal r = 1, n = 1, i = 1;

                    for (; i < 99;)
                        r += n /= i++;

                    return (r + "").Remove(1,1)[d/2] - 48;
                }
            };

            for (int i = 0; i < 100; ++i)
            {
                Console.Write(f(i));
            }
            Console.WriteLine();

            Console.ReadLine();
        }
    }
}

You can ditch the parenthesis around x[j++]/e at c=(x[j++]/e)*n for -2 bytes; Also, I think you can remove both +"" at the two return statements and return an int instead of string, and then add -48 at the second return statement to convert char to int output (for -1 byte).
Kevin Cruijssen

@KevinCruijssen Both work fine thanks!
TheLethalCoder

1

Python 2, 82 bytes

lambda n:`7*ord('L?J$rg$"79n*i.71&<B@[>)!Y8l:.pUo4GZ9c0a%'[n/2])`[n%2+1]

Try it online!

Contains some unprintable ASCII characters. flornquake saved two bytes.


This breaks e.g. for n=64, n=65. Not sure what the best way is to fix that, maybe lambda n:('%02d'%ord('...'[n/2]))[n%2], though there's probably something better.
flornquake

@flornquake darn, you're right. I wrote a fix that's one byte shorter. can't think of anything better
Lynn

Nice. Here's something even shorter, based on your idea: TIO
flornquake

1

brainfuck, 402 bytes

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

Try it online!

Input as character code (e.g. "A" = 65)

Try it online with digit input!

code:

build a value list (3217411852... reversed and each digit incremented by four)
--->+>->+>>+>+>>->->+>+>+>-->->+>+>>>->->+>+>>+>+>->+>>+>+>>+>->->>-->>>->+>>
+>->->->->+>+>>->+>->+>>->>-->->>>->>>+>->->->->>->>+>-->+>+>+>>+>>>+>->->>+>
>->->+>+>->>+>->->>+>->->++[[>+++<-]<+++]>>+>->+>>+>->+>+>+>+>+>+>+>+>->+>->+
>>->->->>+>->->->->+>>->>>>+>+>+>>>+>>->+>>->+>->>->+>->+>>->>+>+>>+>+>+>->>>
+>+>>>>+>->+>+>->+>+>>>->>>+>>>>+>->>>+>>>>->->->->->>+

>,                      get input
[                       while input > 0
  <[-]                      set next previous cell = 0
  >[<+>-]                   copy input cell to that cell
  <-                        and decrement it
]
++++[<+++++++++++>-]    add 44 to it
<.                      print it

0

Neim, 45 bytes

(₃β𝐒𝕣{𝕀𝔼𝐍N𝐭hj\CΓℚ𝕘𝕎𝐓φᚺ𝐲K$mᚠ"2𝕎oξ:{rm(𝕊/𝕚ᛂ𝐗})𝕕

neim isn't made for decimal numbers

Try it online!



0

JavaScript (ES6) + mathjs, 78 bytes

(n,m=math.create({number:"BigNumber"}))=>`${n%2?m.e:m.pi}`.match(/\d/g)[n/2|0]

Zero indexed and works up to 128 numbers (max input of 127).

Test Snippet

let f=
(n,m=math.create({number:"BigNumber"}))=>`${n%2?m.e:m.pi}`.match(/\d/g)[n/2|0]
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.16.0/math.min.js"></script>
<input type=number min=0 value=0 oninput="O.innerHTML=this.value.length>0?f(+this.value):''"><pre id=O>3


0

MATLAB (w/ Symbolic Toolbox), 89 82 bytes

By making use of the Symbolic Toolbox, this answer provides an output without hardcoding the values of pi and e.

As a fun bonus this code as an input can take either a single index, or an array of indices and will simultaneously provide the output value for all index values provided (e.g. providing 1:10 will output the first 10 values).

a=char(vpa({'exp(1)';'pi'},51));
a(a=='.')=[];
n=input('');
a(9+fix(n/2)+56*mod(n,2))

(new lines added for readability, not required for execution so not included in byte count)

Unfortunately the Octave version used by TIO doesn't support symbolic inputs to the vpa function, so can't provide at TIO link.

In MATLAB indexing into the return vector from a function is not possible in the same way as with Octave which means this is a full program rather than just an anonymous function. The program will ask for an input n during execution - this is a one indexed value for which element is required. At the end of the program the value is implicitly printed.

For the program we use the vpa function which provides to 51 decimal places the value of pi and exp(1) (e). This is done symbolically to allow theoretically infinite precision. To expand for more than 100 elements, simply increase the value 51 in the code to increase the range.

Wrapping vpa in char (i.e. char(vpa(...)) ) is necessary to convert the output of the function to a string rather than a symbolic value. The resulting output is the string:

matrix([[2.71828182845904523536028747135266249775724709369996], [3.14159265358979323846264338327950288419716939937511]])

This includes both e and pi to 51 decimal places - enough to allow 100 digits of our output (we have to do a little extra dp than required to avoid printing out rounded values)

In order to index in to this mess, we need to at least get rid of the decimal points so that both strings of digits are contiguous. Originally I used a simple regex replacement of anything which is not a digit with nothing. However I can save 7 bytes by only getting rid of the decimal point using the code:

a(a=='.')=[];

resulting string is now:

matrix([[271828182845904523536028747135266249775724709369996], [314159265358979323846264338327950288419716939937511]])

This contains all the digits we need with both pi and e chunks in consecutive indexes.

We can then convert the supplied index such that odd numbers access the pi chunk and even numbers access the e chunk using the calculation:

9+fix(n/2)+56*mod(n,2)

Accessing that (those) index (indices) in the above string will provide the correct output.


0

Axiom, 148 bytes

g(x,n)==floor(numeric(x)*10^n)::INT rem 10
f(n:NNI):NNI==(m:=digits((n+4)::PI);x:=n quo 2;if n rem 2=1 then r:=g(%e,x)else r:=g(%pi,x);digits(m);r)

0 based array. Results

(10) -> [f(i) for i in 0..20]
   (10)  [3,2,1,7,4,1,1,8,5,2,9,8,2,1,6,8,5,2,3,8,5]
                                            Type: List NonNegativeInteger
(11) -> f(100001)
   (11)  6
                                                    Type: PositiveInteger

0

Google Sheets, 47 Bytes

Note: due to the length of constants stored in Excel and Google Sheets, this solution is only accurate to 20 digits, accordingly

Anonymous Worksheet function that takes input from cell A1 and outputs that digit of Pie to the calling cell

=Mid(.1*If(IsOdd(A1),Pi(),.1*Exp(1)),3+A1/2,1

Hardcoded Version, 112 Bytes

This version fully meets the program specification, but is generally not fun.

Anonymous Worksheet function that returns the nth digit in the 1-indexed list of pie

=Mid("3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919",A1,1

Dividing by 10 to shift decimal point (in stead of SUBSTITUTE) can save a few of bytes in first solution.
Wernisch

0

BFASM, 142 bytes

stk 0
org 0
txt "3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"
in_ r1
rcl r2,r1
out r2

Takes input as ascii character, gives output in form of digit.

Используя наш сайт, вы подтверждаете, что прочитали и поняли нашу Политику в отношении файлов cookie и Политику конфиденциальности.
Licensed under cc by-sa 3.0 with attribution required.