I am trying to find a efficient algorithm in Java to find the repeating decimal part of two integers a
and b
where a/b
.
eg. 5/7 = 0.714258 714258....
I currently only know of the long division method.
I am trying to find a efficient algorithm in Java to find the repeating decimal part of two integers eg. 5/7 = 0.714258 714258.... I currently only know of the long division method. |
|||||
|
I believe that there are two general approaches here, you can essentially "brute force" look for the longest repeating string, or you can solve it as a problem of number theory. It's been a long time since I ran across this problem, but a special case (1 / n) is problem #26 on Project Euler, so you may be able to find more information by searching for efficient solutions for that specific name. One search leads us to Eli Bendersky's website, where he explains his solution. Here's some of the theory from Mathworld's Decimal Expansions page:
My number theory is a bit rusty at the moment, so the best I can do is point you in that direction. |
||||
|
Let So Here's an implementation in Python:
( Note that this implementation (ironically) loops forever if the decimal expansion is finite, but terminates if it's infinite! You can check for this case, though, because |
|||
|
Long division? :/ Turn the result into a string, and then apply this algorithm to it. Use BigDecimal if your string isn't long enough with ordinary types. |
|||||||||||
|