-1

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?

Abhiroop Sarkar
  • 2,251
  • 1
  • 26
  • 45

1 Answers1

1

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

Pshemo
  • 122,468
  • 25
  • 185
  • 269