Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Arbitrary-Precision Arithmetic and Base Conversion Algorithms

Tech Nov 9 22

Large Integer Addition and Subtraction

For handling integers beyond standard data type limits, we implement custom arithmetic operations. The solution must account for both positive and negative numbers with up to 1000 digits.

Key considerations:

  • When both operands are positive: use addition
  • When signs differ: compare absolute values and perform subtraction
  • When both operands are negative: add their absolute values and negate result

Implementation Approach

  1. Parse input strings into digit arrays
  2. Handle sign detection and absolute value extraction
  3. Implement comparison function for magnitude
  4. Create addition and subtraction functions
  5. Apply appropriate operation based on signs
#include <iostream>
#include <vector>
#include <algorithm>

struct LargeNum {
    std::vector<int> digits;
    bool isNegative;
    
    LargeNum() : isNegative(false) {}
};

LargeNum parseNumber(const std::string& s) {
    LargeNum num;
    int start = 0;
    if (s[0] == '-') {
        num.isNegative = true;
        start = 1;
    }
    for (int i = s.length() - 1; i >= start; --i) {
        num.digits.push_back(s[i] - '0');
    }
    return num;
}

bool compareAbsolute(const LargeNum& a, const LargeNum& b) {
    if (a.digits.size() != b.digits.size()) {
        return a.digits.size() > b.digits.size();
    }
    for (int i = a.digits.size() - 1; i >= 0; --i) {
        if (a.digits[i] != b.digits[i]) {
            return a.digits[i] > b.digits[i];
        }
    }
    return true;
}

LargeNum addAbsolute(const LargeNum& a, const LargeNum& b) {
    LargeNum result;
    int carry = 0;
    size_t maxSize = std::max(a.digits.size(), b.digits.size());
    
    for (size_t i = 0; i < maxSize || carry; ++i) {
        int sum = carry;
        if (i < a.digits.size()) sum += a.digits[i];
        if (i < b.digits.size()) sum += b.digits[i];
        result.digits.push_back(sum % 10);
        carry = sum / 10;
    }
    return result;
}

LargeNum subtractAbsolute(const LargeNum& a, const LargeNum& b) {
    LargeNum result;
    int borrow = 0;
    
    for (size_t i = 0; i < a.digits.size(); ++i) {
        int diff = a.digits[i] - borrow;
        if (i < b.digits.size()) diff -= b.digits[i];
        if (diff < 0) {
            diff += 10;
            borrow = 1;
        } else {
            borrow = 0;
        }
        result.digits.push_back(diff);
    }
    
    while (result.digits.size() > 1 && result.digits.back() == 0) {
        result.digits.pop_back();
    }
    return result;
}

LargeNum calculate(const LargeNum& a, const LargeNum& b) {
    if (!a.isNegative && !b.isNegative) {
        return addAbsolute(a, b);
    }
    if (a.isNegative && b.isNegative) {
        LargeNum result = addAbsolute(a, b);
        result.isNegative = true;
        return result;
    }
    LargeNum absA = a, absB = b;
    absA.isNegative = absB.isNegative = false;
    
    if (compareAbsolute(absA, absB)) {
        LargeNum result = a.isNegative ? subtractAbsolute(absA, absB) : subtractAbsolute(absA, absB);
        result.isNegative = a.isNegative;
        return result;
    } else {
        LargeNum result = b.isNegative ? subtractAbsolute(absB, absA) : subtractAbsolute(absB, absA);
        result.isNegative = !a.isNegative;
        return result;
    }
}

void display(const LargeNum& num) {
    if (num.isNegative && !(num.digits.size() == 1 && num.digits[0] == 0)) {
        std::cout << '-';
    }
    for (auto it = num.digits.rbegin(); it != num.digits.rend(); ++it) {
        std::cout << *it;
    }
    std::cout << std::endl;
}

int main() {
    std::string x, y;
    while (std::cin >> x >> y) {
        LargeNum a = parseNumber(x);
        LargeNum b = parseNumber(y);
        LargeNum result = calculate(a, b);
        display(result);
    }
    return 0;
}

Decimal Number Addition with Floating Points

This implementation handles addition of non-negative decimal numbers with fractional parts, maintaining precision for both integer and decimal components.

Algorithm Design

  1. Separate integer and fractional parts
  2. Align fractional parts by padding shorter one with zeros
  3. Add fractional components first, carrying overflow to integer part
  4. Add integer components with any remaining carry
#include <iostream>
#include <vector>
#include <algorithm>

struct Decimal {
    std::vector<int> integer;
    std::vector<int> fraction;
};

Decimal parseDecimal(const std::string& s) {
    Decimal num;
    size_t dotPos = s.find('.');
    size_t fracStart = (dotPos == std::string::npos) ? s.length() : dotPos - 1;
    
    for (int i = fracStart; i >= 0; --i) {
        if (s[i] != '.') {
            num.integer.push_back(s[i] - '0');
        }
    }
    
    if (dotPos != std::string::npos) {
        for (size_t i = s.length() - 1; i > dotPos; --i) {
            num.fraction.push_back(s[i] - '0');
        }
    }
    
    return num;
}

Decimal addDecimals(const Decimal& a, const Decimal& b) {
    Decimal result;
    
    size_t maxFracLen = std::max(a.fraction.size(), b.fraction.size());
    int carry = 0;
    
    // Add fractional parts
    for (size_t i = 0; i < maxFracLen; ++i) {
        int sum = carry;
        if (i < a.fraction.size()) sum += a.fraction[i];
        if (i < b.fraction.size()) sum += b.fraction[i];
        result.fraction.push_back(sum % 10);
        carry = sum / 10;
    }
    
    // Add integer parts
    size_t maxIntLen = std::max(a.integer.size(), b.integer.size());
    for (size_t i = 0; i < maxIntLen || carry; ++i) {
        int sum = carry;
        if (i < a.integer.size()) sum += a.integer[i];
        if (i < b.integer.size()) sum += b.integer[i];
        result.integer.push_back(sum % 10);
        carry = sum / 10;
    }
    
    return result;
}

void displayDecimal(const Decimal& num) {
    // Display integer part
    for (auto it = num.integer.rbegin(); it != num.integer.rend(); ++it) {
        std::cout << *it;
    }
    
    std::cout << ".";
    
    // Display fractional part without trailing zeros
    int lastNonZero = num.fraction.size() - 1;
    while (lastNonZero >= 0 && num.fraction[lastNonZero] == 0) {
        lastNonZero--;
    }
    
    for (int i = lastNonZero; i >= 0; --i) {
        std::cout << num.fraction[i];
    }
    
    if (lastNonZero < 0) {
        std::cout << "0";
    }
    
    std::cout << std::endl;
}

int main() {
    int cases;
    std::cin >> cases;
    while (cases--) {
        std::string x, y;
        std::cin >> x >> y;
        Decimal a = parseDecimal(x);
        Decimal b = parseDecimal(y);
        Decimal sum = addDecimals(a, b);
        displayDecimal(sum);
    }
    return 0;
}

Base Conversion Between Arbitrary Number Systems

This implementation converts numbers from any base m to base n (2 ≤ m, n ≤ 36), handling both digits and alphabetic characters for values ≥ 10.

Conversion Method

  1. Parse input string into digit values
  2. Repeatedly divide by target base, collecting remainders
  3. Use base-specific multiplication during division
  4. Output remainders in correct order
#include <iostream>
#include <vector>
#include <cctype>

struct Number {
    std::vector<int> digits;
    int base;
};

Number parseBase(const std::string& s, int base) {
    Number num;
    num.base = base;
    
    for (char c : s) {
        int value;
        if (isdigit(c)) {
            value = c - '0';
        } else {
            value = toupper(c) - 'A' + 10;
        }
        num.digits.push_back(value);
    }
    return num;
}

Number divideByBase(Number& num, int targetBase, int& remainder) {
    Number result;
    result.base = targetBase;
    remainder = 0;
    
    for (int digit : num.digits) {
        int currentValue = remainder * num.base + digit;
        result.digits.push_back(currentValue / targetBase);
        remainder = currentValue % targetBase;
    }
    
    // Remove leading zeros
    while (result.digits.size() > 1 && result.digits[0] == 0) {
        result.digits.erase(result.digits.begin());
    }
    
    return result;
}

std::string convertBase(const std::string& input, int fromBase, int toBase) {
    Number num = parseBase(input, fromBase);
    std::vector<int> remainders;
    
    // Convert until number becomes zero
    while (!(num.digits.size() == 1 && num.digits[0] == 0)) {
        int rem;
        num = divideByBase(num, toBase, rem);
        remainders.push_back(rem);
    }
    
    // Build result string
    std::string result;
    for (auto it = remainders.rbegin(); it != remainders.rend(); ++it) {
        if (*it < 10) {
            result += std::to_string(*it);
        } else {
            result += 'A' + (*it - 10);
        }
    }
    
    return result.empty() ? "0" : result;
}

int main() {
    int fromBase, toBase;
    std::string number;
    
    while (std::cin >> fromBase >> toBase >> number) {
        std::cout << convertBase(number, fromBase, toBase) << std::endl;
    }
    
    return 0;
}

Binary Reversal and Conversion

This specialized conversion takes a decimal number, converts it to binary, reverses the binary representation, and converts back to decimal.

#include <iostream>
#include <vector>
#include <algorithm>

std::vector<int> decimalToBinary(long long n) {
    std::vector<int> binary;
    if (n == 0) {
        binary.push_back(0);
        return binary;
    }
    
    while (n > 0) {
        binary.push_back(n % 2);
        n /= 2;
    }
    
    std::reverse(binary.begin(), binary.end());
    return binary;
}

long long binaryToDecimal(const std::vector<int>& binary) {
    long long result = 0;
    for (int bit : binary) {
        result = result * 2 + bit;
    }
    return result;
}

int main() {
    long long number;
    while (std::cin >> number) {
        std::vector<int> binary = decimalToBinary(number);
        std::reverse(binary.begin(), binary.end());
        long long result = binaryToDecimal(binary);
        std::cout << result << std::endl;
    }
    return 0;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.