Convert Ratio To Decimal
May 15, 2015
Our exercise today is an interview question. Like all of our interview questions, it works better if you put some pressure on yourself to simulate the pressure of an interview; so, for today’s exercise you must complete your solution in fifteen minutes:
Given two positive integers, a numerator and a denominator, and a third positive integer, the number of digits, write the decimal ratio of numerator to denominator to the requested number of digits. For instance, given a numerator of 3227, a denominator of 557, and a number of digits of 30, the correct output is 5.793536804308797127468581687612.
Your task is to write a program to convert ratios to decimals. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Python.
from decimal import Decimal, getcontext def round_frac1(num, den, digits): getcontext().prec = digits return Decimal(num) / Decimal(den) def round_frac2(num, den, digits): res = ["" if num >= 0 else "-"] div, mod = divmod(abs(num), den) res += [str(div), "."] for d in range(digits): if mod == 0: break div, mod = divmod(mod * 10, den) res.append(str(div)) return "".join(res) print(round_frac1(3227, 557, 31)) # 5.793536804308797127468581687612 print(round_frac2(3227, 557, 30)) # 5.793536804308797127468581687612A quick ‘n dirty Haskell version.
-- The result of a/b with n digits after the decimal point. divide n a b = let (q, r) = a `quotRem` b in show q ++ "." ++ concatMap show (take n (r `fr` b)) where a `fr` b = let (q, r) = (10*a) `quotRem` b in q : (r `fr` b)A couple of examples in ghci:
In C++
#include
using namespace std;
int main()
{
int den,num,dig,temp1,temp2;
cout <> den;
cout <> num;
cout <> dig;
cout << num/den << "."; // Whole number part of decimal followed by decimal point
temp1=num;
for (int i=0;i<30;i++)
{
temp2=(temp1%den)*10;
cout << temp2/den;
temp1=temp2%den;
}
return 0;
}
In C++
Clojure
I admit, it took me longer than 15 minutes..
(defn long-division [nom denom decimals] (loop [result (str (quot nom denom) ".") nom (* (mod nom denom) 10) decimals decimals] (if (> decimals 0 ) (recur (str result (quot nom denom)) (* (mod nom denom) 10) (dec decimals)) result))) (println (long-division 3227 557 30))