Tuesday, June 9, 2015

Google: A/B with first N digits of a rational Number

public void print(int num, int denom, int numDigits) {
    StringBuffer sb = new StringBuffer();

    // Compute number to left of decimal
    sb.append(num / denom);
    sb.append('.');
    num = (num % denom) * 10;

    // Compute each digit to the right of the decimal
    while (numDigits > 0) {
        sb.append(num / denom);
        num = (num % denom) * 10;
        numDigits--;
    }
    System.out.println(sb.toString());
}

No comments:

Post a Comment