I was tasked to find a digit of kth position after the decimal point of a fraction(a/b).
Yesterday I found out this algorithm.
To get any digit after the decimal point, I generate a variable called rem and make a loop
for (int i = 1; i <= k+1; i++)
{
rem = a%b;
a = rem*10;
}
cout << a/b;
the loop will return a value being the kth digit after the decimal point.
However the task require me to calculate with a,b,k being very large number ( less or equal to 10e18), so it's sure that the code will exceed the time limit.
- Find the number of the digits before the repetend. It's the greater of the numbers of 2 and 5 factors in the denominator.
- If the k doesn't exceed the number of digits, run the for loop.
- Else, we will still run the for loop to k+1. Store the value of the remainder of the division in a variable x.
- Run a while loop with the same content above until the remainder again have the value of x. Since then, store every quotient of the division into an array name qut.
- After the while loop terminates, the array will have stored every digit inside the repetend. According to the number of the digits inside the array, we can calculate the kth digit.
However, this algorithm still prove to be time consuming because in the case of a and b are two consecutive integer, the repetend become very large. Can you help me with any idea?
integers, then how can they be less than or equal to 10e18?? As far as I know, the highest limit of integer in c++ (which is that ofunsigned long intis about4.29e9. - progyammeruint64_t. It doesn't have to exist, but if it does it will hold 10e18. - Martin Bonner supports Monica