How do you calculate recurring numbers?

advertisements

Given two integers a and b, how would I go about calculating the repeating decimal of a / b? This can be in any language; whatever it's easiest for you to express it in.


You can do it with long division. Calculate a single digit at a time and subtract to get a remainder, which you multiply by 10 to get the numerator for the next step. When this new numerator matches one of the previous numerators, you know you're going to repeat from that point forward. You just need to keep a stack of previous numerators and search through it at each iteration.