Finding the Particular digit of Pi using TakeWhile
Finding the Particular digit of Pi using TakeWhile
TakeWhile[First[RealDigits[Pi, 10, 100]], # != 7 &]
This is used to calculate the first occurrence of 7 but how to get the 20th occurrence of 7.
2 Answers
2
In three steps so that it is easier to understand what's going on:
First[RealDigits[Pi, 10, 1000]] // Short
Position[%, 7][[20, 1]]
%%[[1 ;; % - 1]]
TakeWhile
ClearAll[digitsUpToMthK]
digitsUpToMthK[mth_, k_, n_] := Module[t = 0,
TakeWhile[First[RealDigits[Pi, 10, n]], Or[# != k, (++t) < mth] &]]
Examples:
digitsUpToMthK[3, 7, 10000]
3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6, 4, 3, 3, 8, 3, 2, 7, 9, 5, 0, 2, 8, 8, 4, 1, 9
Length @ digitsUpToMthK[20, 7, 1000]
301
Short @ digitsUpToMthK[20, 7, 1000]
3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6, 4, 3, 3, 8, 3, 2, 7, 9, 5, 0, 2, 8, 8,
<< 230 >>,
4, 8, 6, 1, 0, 4, 5, 4, 3, 2, 6, 6, 4, 8, 2, 1, 3, 3, 9, 3, 6, 0, 7, 2, 6, 0, 2, 4, 9, 1, 4, 1, 2, 7, 3
If you need the position of $m$th occurence of a given digit, you can use LengthWhile:
LengthWhile
ClearAll[posOfMthK]
posOfMthK[mth_, k_, n_] := Module[t = 0,
1 + LengthWhile[First[RealDigits[Pi, 10, n]], Or[# != k, (++t) < mth] &]]
Examples:
posOfMthK[20, 7, 100000]
302
posOfMthK[100, 3, 100000]
937
Thanks for contributing an answer to Mathematica Stack Exchange!
But avoid …
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.