Все знают пи математическую константу, отношение длины окружности к ее диаметру.
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
dumb
просто означает неинтересный без каких-либо особых свойств.pei
не такpie
Ответы:
Mathematica, 50 bytes
1-indexed
источник
Riffle
, but my solution comes up one byte short:RealDigits[If[OddQ@#,Pi,E],10,#][[1,Ceiling[#/2]]]
&Haskell,
154147146 bytes, NO HARDCODING OR USE OF BUILTIN CONSTANTSThis solution calculates e and pi using infinite series and stores them in arbitrary-precision fixed-point integers (Haskell's built-in
Integer
type and itsRational
extension).Ungolfed:
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.источник
Taxi, 749 bytes
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 iteratesn
down and removes the first character in the string each time. Whenn=0
, output the first character. This is one-indexed.Un-golfed / formatted:
источник
Python 2, 88 bytes
-4 bytes thanks to the base conversion idea of @EriktheOutgolfer.
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.Try it online!
Python 2, 114 bytes
I honestly think the shortest solution is hardcoding, since Python doesn't have useful built-ins.Try it online!
Python 2, 114 bytes
Equivalent solution by @totallyhuman.
Try it online!
источник
05AB1E, 10 bytes
Explanation:
0-indexed.
Try it online!
источник
ž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 theJ
oin would join those pairs instead of everything. 9 bytes are still possible by replacingJ
withS
in the new version however, whereS
makes it a flattened list of chars/digitsPython 3,
8380 bytes0-indexed.
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.источник
Polyglot, 108 bytes
Works in:
I think this is the shortest you can do in C# seeing as it is 252 bytes to find the Nth decimal of pi.
источник
Java 8,
420417413404380358 (calculated) &115110 (hardcoded) bytesCalculated (
420417413404380358):Try it here.
Prove it outputs correct result for required 100 items.
Hardcoded: (
115110 bytes):Try it online.
0-indexed
-9 and -5 bytes thanks to @Nevay.
-24 bytes thanks to @ceilingcat.
You've asked for it.. ;)
Java's built-in
Math.PI
andMath.E
are doubles, which have a max precision of just 16. Therefore, we'll have to calculate both values ourselves usingjava.math.BigInteger
and/orjava.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 usesBigDecimal
however.The resulting
p
ande
are therefore:31415...
and2.718...
.Could probably golf it by only using
BigDecimal
, but was giving some incorrect answers for PI, so I now use bothBigDecimal
andBigInteger
.Explanation:
источник
(d+=2)
to++d
andreturn p%10+1
to justreturn p%10
.You've asked for it.. ;)
Hey, I like your first one better. I got way more hardcoded answers than I expected...charAt(n+1>>1)
and 5 bytes in your hardcoded version by using a method reference"..."::charAt
.Seed, 6015 bytes
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.
источник
Excel, 113 bytes
1-indexed
PI()
is only accurate up to 15 digits. Similar forEXP(1)
.6042 byte solution that works for Input<=30
(-18 bytes thanks to @Adam)источник
if(...)
statement:=MID(IF(ISODD(b1),PI(),EXP(1)/10)/10,b1/2+3,1)
.Can't get around the imprecision ofpi()
andexp()
, though05AB1E, 13 bytes
Try it online!
Similar to Magic's answer, but kinda different.
Explanation:
источник
Python 2 + SymPy,
7063 bytesTry it online!
источник
Japt, 55 bytes
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:
Test it online!
источник
Julia, 63 bytes
1-indexed
Converts pi or e to a string, removes the decimal place, and then calls the appropriate digit. Returns a character representation of the digit.
источник
Seed,
58525794Based on TehPers Befunge answer.
источник
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.
источник
05AB1E, 14 bytes
Try it online!
This answer is 0-indexed.
источник
'.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<
.),
since the zip does this implicitly, but I see it's than almost exactly the same as the other 10-byte answer..Python 3 + SymPy, 109 Bytes
0-indexed Try it online!
Beat hardcoding by 5 bytes!! But could probably be better. But beating hardcoding makes me feel good :)
источник
Pyth, 35 bytes
Test suite
Since Pyth doesn't have built-in arbitrary precision pi and e constants, I calculate them directly.
Calculating pi:
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:
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.
источник
MATLAB, 93 Bytes
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.
источник
n
, it will produce thenth
digit of the Pie sequence. You can also reduce your bytecount by reducing your variable names to a single charinput('')
in place ofinput('n')
C# + BigDecimal,
377372 bytesSaved 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:
источник
x[j++]/e
atc=(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).Python 2, 82 bytes
Try it online!
Contains some unprintable ASCII characters. flornquake saved two bytes.
источник
lambda n:('%02d'%ord('...'[n/2]))[n%2]
, though there's probably something better.brainfuck, 402 bytes
Try it online!
Input as character code (e.g. "A" = 65)
Try it online with digit input!
code:
источник
Neim, 45 bytes
neim isn't made for decimal numbers
Try it online!
источник
Befunge, 105 bytes
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 the3
on the first line.источник
JavaScript (ES6) + mathjs, 78 bytes
Zero indexed and works up to 128 numbers (max input of 127).
Test Snippet
источник
MATLAB (w/ Symbolic Toolbox),
8982 bytesBy 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).
(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 ofpi
andexp(1)
(e). This is done symbolically to allow theoretically infinite precision. To expand for more than 100 elements, simply increase the value51
in the code to increase the range.Wrapping
vpa
inchar
(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: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:
resulting string is now:
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:
Accessing that (those) index (indices) in the above string will provide the correct output.
источник
Axiom, 148 bytes
0 based array. Results
источник
Google Sheets, 47 Bytes
Anonymous Worksheet function that takes input from cell
A1
and outputs that digit of Pie to the calling cellHardcoded 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
источник
BFASM, 142 bytes
Takes input as ascii character, gives output in form of digit.
источник