Print first k digits of 1/n where n is a positive integer - GeeksQuiz
Given a positive integer n, print first k digits after point in value of 1/n. Your program should avoid overflow and floating point arithmetic.
Read full article from Print first k digits of 1/n where n is a positive integer - GeeksQuiz
Given a positive integer n, print first k digits after point in value of 1/n. Your program should avoid overflow and floating point arithmetic.
Let us consider an example n = 7, k = 3. The first digit of 1/7 is ‘1’, it can be obtained by doing integer value of 10/7. Remainder of 10/7 is 3. Next digit is 4 which can be obtained by taking integer value of 30/7. Remainder of 30/7 is 2. Next digits is 2 which can be obtained by taking integer value of 20/7
void print(int n, int k){ int rem = 1; // Initialize remainder // Run a loop k times to print k digits for (int i = 0; i < k; i++) { // The next digit can always be obtained as // doing (10*rem)/10 cout << (10 * rem) / n; // if rem==0, print directly // Update remainder rem = (10*rem) % n; }}