I want to find the value of 22/7 to 10^6 places of decimals in java. Is it possible to do this within a short compile time?
-
1See the question http://stackoverflow.com/questions/15164636/get-all-decimal-places-in-a-number-after-division/15164795#comment21356531_15164795 – Cyrille Ka Mar 03 '13 at 19:27
-
1`22/7` is rational. It's not difficult to compute to one million places. Computing `pi` to one million places would be harder. – John Dvorak Mar 03 '13 at 19:28
-
2Short compile time is trivial. Do you mean short execution time? – Ted Hopp Mar 03 '13 at 19:31
-
2`22/7` is exactly `3.(142857)` where parentheses denote the periodic part. – John Dvorak Mar 03 '13 at 19:31
-
yes i meant short execution time – Abhiroop Sarkar Mar 03 '13 at 19:38
-
1`103993/33102 = 3.1(415926530119026040722614947737296840070086399613316)`; see http://www.wolframalpha.com/input/?i=103993%2F33102 – John Dvorak Mar 03 '13 at 19:40
-
Or how to memorize 11 digits to obtain 10 valid digits. Yay! – Léon Pelletier Jun 06 '15 at 21:54
1 Answers
Take a pen and paper and try to divide 22/7. It will look like this
03,142857142857
---
22:7
0
--
22
21
--- < now we calculate fractal part so we will add zeros at the end
10 # 10 contains 7 only one time -> 1
7
---
30 # 30 contains 7 four times -> 4
28
---
20 ->2
14
---
60 ->8
56
---
40 ->5
35
---
50 ->7
49
---
10 # but wee already calculated this state of fractal part
# so from now on it will repeat again and again and again...
# giving ...142857|142857|142857...
So 22/7 = 3,(142857)
. Knowing that periodic part starts at first position of fractal part, and it contains six digits we can calculate that 10th
digit is 8
(forth digit of periodic part), 20th
position is 4
(second digit of periodic part). It is easy to notice that if periodic part starts at first position then n-th digit will be (n)mod(number of digits in period) so 10 % 6 = 4
and fourth digit in periodic part is 8
, 20 % 6 = 2
and second digit in periodic part is 4
.
So you probably can implement your own algorithm that will cache (lets say in some map that remembers order of placed key->value pairs) and will try to calculate that fractal part until
- it finds repeating part
- at some point (like in 5/4 = 1.250000) fractal part will end
- will calculate
n-th
digit without finding periodic part (2nd digit of 22/7 can be returned before finding period)
Additional info. Period can't be longer then number you used to divide since minimal value of X%Y
is 0
(and in that case we would stop dividing) and max value of X%Y
is Y-1
, so only digits between 1 and Y-1 can be used in periodic part so its max length will be Y-1

- 122,468
- 25
- 185
- 269