35
\$\begingroup\$

Everybody knows pi the mathematical constant, the ratio of a circle's circumference to its diameter.

3.14159265358979323846264338327950288419716939937510...

You probably also know e the mathematical constant, the base of a natural logarithm.

2.71828182845904523536028747135266249775724709369996...

But... do you know pie? It is one of the most important constants (to me). It is the digits of pi and e interleaved.

32.1741185298216852385485997094352233854366206248373...

As a decimal expansion:

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

This is OEIS sequence A001355.

KEYWORD: nonn,base,dumb,easy

It is a very dumb sequence.

Challenge

Write a program/function that takes a non-negative integer n and outputs the nth digit of pie.

Specifications

  • Standard I/O rules apply.
  • Standard loopholes are forbidden.
  • 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).
  • The output for 2 or 3 is not a decimal point.
  • Your solution can either be 0-indexed or 1-indexed but please specify which.
  • This challenge is not about finding the shortest approach in all languages, rather, it is about finding the shortest approach in each language.
  • Your code will be scored in bytes, usually in the encoding UTF-8, unless specified otherwise.
  • Built-in functions that compute this sequence are allowed but including a solution that doesn't rely on a built-in is encouraged.
  • Explanations, even for "practical" languages, are encouraged.

Test cases

These are 0-indexed.

Input   Output

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

In a few better formats:

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
\$\endgroup\$
  • 8
    \$\begingroup\$ According to the OEIS, the keyword dumb simply means uninteresting with no properties special to it. \$\endgroup\$ – Okx Aug 11 '17 at 15:19
  • 1
    \$\begingroup\$ @Downvoter Any reason, perhaps? \$\endgroup\$ – totallyhuman Aug 12 '17 at 0:55
  • 21
    \$\begingroup\$ One could argue that the result is pei, not pie \$\endgroup\$ – Zaid Aug 12 '17 at 10:35
  • 1
    \$\begingroup\$ I didn't do the down vote, but maybe because you didn't ask this on 3/14 ;) \$\endgroup\$ – txtechhelp Aug 12 '17 at 20:01
  • 1
    \$\begingroup\$ At 1:59pm, @txtechhelp? ;) \$\endgroup\$ – WallyWest Aug 24 '18 at 1:16

27 Answers 27

10
\$\begingroup\$

Mathematica, 50 bytes

1-indexed

(Riffle@@(#&@@RealDigits[#,10,5!]&/@{Pi,E}))[[#]]& 
\$\endgroup\$
  • \$\begingroup\$ Can you explain how this works? \$\endgroup\$ – Stevoisiak Aug 11 '17 at 16:55
  • \$\begingroup\$ it's easy. It takes 120(5!) elements of each and riffle them \$\endgroup\$ – J42161217 Aug 11 '17 at 16:57
  • \$\begingroup\$ 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]]]& \$\endgroup\$ – Mark S. Aug 12 '17 at 4:06
  • \$\begingroup\$ This appears not to work. It returns a single digit. \$\endgroup\$ – DavidC Aug 12 '17 at 20:23
  • \$\begingroup\$ @DavidC Yes!.."outputs the nth digit of pie" Exactly! why did you downvote??? \$\endgroup\$ – J42161217 Aug 12 '17 at 20:26
8
\$\begingroup\$

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.
\$\endgroup\$
7
\$\begingroup\$

Haskell, 154 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))|k<-r],[1%product[1..k]|k<-r]]!!mod n 2)!!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.

\$\endgroup\$
6
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Before downvoting, take your time to search for a shorter solution. \$\endgroup\$ – Mr. Xcoder Aug 11 '17 at 15:29
  • \$\begingroup\$ Equivalent byte count. \$\endgroup\$ – totallyhuman Aug 11 '17 at 15:30
  • \$\begingroup\$ @totallyhuman Thanks \$\endgroup\$ – Mr. Xcoder Aug 11 '17 at 15:30
  • 8
    \$\begingroup\$ The equivalent solution that you edited in is actually equivalent code, not equivalent byte count. :P \$\endgroup\$ – totallyhuman Aug 11 '17 at 16:18
  • 1
    \$\begingroup\$ @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! \$\endgroup\$ – Mr. Xcoder Aug 12 '17 at 13:58
5
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ Too many 05AB1Es... :P \$\endgroup\$ – Mr. Xcoder Aug 11 '17 at 15:12
  • \$\begingroup\$ @Mr.Xcoder Well, 05AB1E is the language with the pi and e builtin... \$\endgroup\$ – Okx Aug 11 '17 at 15:13
  • \$\begingroup\$ @Mr.Xcoder There are builtins that's why. \$\endgroup\$ – Erik the Outgolfer Aug 11 '17 at 15:13
  • \$\begingroup\$ @totallyhuman no it doesn't. \$\endgroup\$ – Erik the Outgolfer Aug 11 '17 at 15:16
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ JS polyglot :-) \$\endgroup\$ – Arnauld Aug 11 '17 at 15:51
  • \$\begingroup\$ @Arnauld Updated :) \$\endgroup\$ – TheLethalCoder Aug 11 '17 at 15:54
  • 7
    \$\begingroup\$ This isn't a Java Polyglot! You can't index into Non-Array Objects in Java. \$\endgroup\$ – Roman Gräf Aug 11 '17 at 20:47
  • 1
    \$\begingroup\$ This technically works but I downvoted because it's a) not very competitive and b) extremely boring and trivial. \$\endgroup\$ – HyperNeutrino Aug 12 '17 at 2:18
  • 2
    \$\begingroup\$ @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... \$\endgroup\$ – TheLethalCoder Aug 13 '17 at 8:07
4
\$\begingroup\$

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

Calculated (420 417 413 404):

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

Hardcoded: (115 bytes):

"3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919"::charAt

0-indexed

-9 and -5 bytes thanks to @Nevay.

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

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

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=p=BigInteger.TEN.pow(x).multiply(new BigInteger("2"));
                              //  Temp BigInteger (both `p` and `a` start at 10^25000*2)
  for(;i<x;                   //  Loop (1) 99 times (the higher the better precision)
    e=e.add(                  //    After every iteration: Add the following to `e`:
     e.ONE.divide(f,new MathContext(x,RoundingMode.HALF_UP))))
                              //     1/`f` (RoundingMode is mandatory for BigDecimal divide)
    f=f.multiply(new BigDecimal(i++));
                              //   Multiple `f` with `i`
                              //  End of loop (1) (implicit / single-line body)
  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(a))               //    After every iteration, add `a` to `p`
    a=a.multiply(new BigInteger(i+""))
                              //   Multiply `a` with `i`
       .divide(new BigInteger(2*i+++1+""));
                              //   and divide that by `2*i+1`
                              //  End of loop (2) (implicit / single-line body)
  // 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 integer to String:
        .charAt(n+1>>1);      //   `n+1` signed right shift 1 bit
}                             // End of method
\$\endgroup\$
  • \$\begingroup\$ Not sure if it will help you but my C# algorithm for calculating pi came in at 8 bytes shorter than your Java version. \$\endgroup\$ – TheLethalCoder Aug 14 '17 at 11:17
  • \$\begingroup\$ 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. \$\endgroup\$ – TheLethalCoder Aug 14 '17 at 11:24
  • \$\begingroup\$ @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.. \$\endgroup\$ – Kevin Cruijssen Aug 14 '17 at 11:34
  • 1
    \$\begingroup\$ You've asked for it.. ;) Hey, I like your first one better. I got way more hardcoded answers than I expected... \$\endgroup\$ – totallyhuman Aug 14 '17 at 15:45
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Nevay Aug 14 '17 at 15:59
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ How? Just... how? \$\endgroup\$ – NieDzejkob Aug 13 '17 at 14:06
3
\$\begingroup\$

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)
\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Adam Aug 11 '17 at 21:20
2
\$\begingroup\$

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]
\$\endgroup\$
2
\$\begingroup\$

Python 2 + SymPy, 70 63 bytes

lambda n:int(N([pi,E][n%2],50)*10**(n/2)%10)
from sympy import*

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.
\$\endgroup\$
  • \$\begingroup\$ 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 <.) \$\endgroup\$ – Kevin Cruijssen Nov 19 '18 at 14:16
  • \$\begingroup\$ 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.. \$\endgroup\$ – Kevin Cruijssen Nov 19 '18 at 14:17
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Welcome to the site! \$\endgroup\$ – DJMcMayhem Aug 12 '17 at 20:17
  • \$\begingroup\$ Thanks, I've been browsing Code Golf for quite a while, and finally decided to give it a go myself. \$\endgroup\$ – a13a22 Aug 12 '17 at 20:20
  • \$\begingroup\$ 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 \$\endgroup\$ – Taylor Scott Aug 13 '17 at 17:33
  • \$\begingroup\$ 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? \$\endgroup\$ – a13a22 Aug 13 '17 at 17:41
  • \$\begingroup\$ 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') \$\endgroup\$ – Taylor Scott Aug 13 '17 at 18:14
1
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender Aug 13 '17 at 19:29
1
\$\begingroup\$

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();
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ 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). \$\endgroup\$ – Kevin Cruijssen Aug 14 '17 at 13:04
  • \$\begingroup\$ @KevinCruijssen Both work fine thanks! \$\endgroup\$ – TheLethalCoder Aug 14 '17 at 13:25
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – flornquake Aug 15 '17 at 20:54
  • \$\begingroup\$ @flornquake darn, you're right. I wrote a fix that's one byte shorter. can't think of anything better \$\endgroup\$ – Lynn Aug 16 '17 at 5:45
  • \$\begingroup\$ Nice. Here's something even shorter, based on your idea: TIO \$\endgroup\$ – flornquake Aug 16 '17 at 11:30
0
\$\begingroup\$

Neim, 45 bytes

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

neim isn't made for decimal numbers

Try it online!

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

Befunge, 105 bytes

3217411852982168523854859970943522338543662062483734873123759256062284894717957712649730999336795919&0g,@

Does not work on TIO because it seems to wrap lines internally at 80 characters for some reason. You can get it to work on TIO by putting each digit on a new line, and having the &0g,@ after the 3 on the first line.

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

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

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

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.

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

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
\$\endgroup\$
-1
\$\begingroup\$

Python2, 80 76 bytes

from math import*
lambda n:([(3,2)]+zip('%.49f'%pi,'%.49f'%e)[2:])[n/2][n%2]

0-indexed.

EDIT: Saved 4 bytes by removing parens around pi and e. (Thanks LyricLy!)

EDIT: I can't find a python library that matches sequence A001355 past index 33 (math, numpy, sympy, mpmath with increased precision). Thanks to flornquake for pointing out the precision issue.

Explanation:

from math import*    # built-in math module, contains the constants 'pi' and 'e'
lambda n:            # an anonymous function that takes input n
    ( [(3,2)]        # the first digits of the sequence
    +
    zip(             # interleave contents. (1,2,3),(4,5,6) -> (1,4,2,5,3,6)
        '%.49f'%(pi),'%.49f'%(e)    # convert constants to strings with length
                                    # after the decimal == 49.
    )[2:])           # get sequence after first tow sets (3,2) and ('.', '.')
[n/2][n%2]           # sequence is currently like [(3, 2), (1, 7), (4, 1), (1, 8) ...]
                     # get pair indicated by n by dividing by 2 (integer division, floors)
                     # then get item in pair by modding by 2 (0 or 1)
                     # So, sequence item 7 would be pair 3, item 1 == 8.
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! Consider adding a try it online link so that users can test your submission. Great first answer, by the way. \$\endgroup\$ – LyricLy Aug 11 '17 at 22:15
  • 1
    \$\begingroup\$ You can save 4 bytes by removing the parentheses around pi and e: Try it online! \$\endgroup\$ – LyricLy Aug 11 '17 at 22:24
  • 5
    \$\begingroup\$ This doesn't quite work because the precision of pi and e isn't enough. For higher n you get false results. \$\endgroup\$ – flornquake Aug 11 '17 at 22:33
-1
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Dividing by 10 to shift decimal point (in stead of SUBSTITUTE) can save a few of bytes in first solution. \$\endgroup\$ – Wernisch Aug 14 '17 at 8:29

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.