Last Updated: 3 Mar, 2021

Find Division Upto Given Decimal Places

Easy
Asked in companies
MicrosoftIBM

Problem statement

You are given three integers ‘X’, ‘Y’ and ‘N’. Find the value of division X / Y up to ‘N’ decimal places.

You should return a string that represents the value X / Y up to ‘N’ decimal places. This string must have ‘N’ digits after decimals. You don’t need to round off the result to ‘N’ decimal places, just find the first ‘N’ places after decimals.

Note:

1. It is guaranteed that division X / Y is always finite.

Example:

Consider X = 5, Y = 4 and N = 5, then you should return “1.25000”. 
Note, here we add 3 trailing zeros so that it has exactly 5 digits after decimals.    
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases, then ‘T’ test cases follow.

The first and only line of each test case consists of three space-separated integers, ‘X’, ‘Y’, ‘N’ respectively.    
Output format :
For each test case, print in a separate line, a string representing the value X / Y  up to ‘N’ decimal places, and it must have ‘N’ digits after decimals.

Note:

You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
-10^8  <= X <= 10^8
-10^8  <= Y <= 10^8
Y != 0
1 <= N <= 10^4

Time limit: 1 sec

Approaches

01 Approach

Following is the detailed algorithm :

 

  • Create an empty string ‘RESULT’.
  • If exactly one of ‘X’ or ‘Y’ is negative then append ‘-’ in ‘RESULT’.
  • Do floor division of the absolute value of ‘X’ by the absolute value of  ‘Y’, i.e abs(‘X’) / abs(‘Y’), and append the value obtained in ’RESULT’ after converting it into string.
  • Append ‘.’ in ‘RESULT’.
  • Initialize an integer ‘REM’ := abs(‘X’) % abs(‘Y’).
  • Run a loop where ‘i’ ranges from 1 to ‘N’ and in each iteration do the following
    • Multiiply ‘REM’ by 10, i.e do ‘REM’ := ‘REM’ * 10.
    • Initialize an integer variable ‘DIGIT’ by the value obtained by floor division of ‘REM’ by the absolute value of ‘Y’, i.e  ‘REM’ := floor( ‘REM’ / abs(‘Y’) );
    • Do ‘REM’ := ‘REM’ % abs(‘Y’).
    • Append ‘DIGIT’ in ‘RESULT’ after converting it into the string.
  • Return ‘RESULT’.