Post

Number Theory

Number theory is a branch of pure mathematics devoted primarily to the study of the integers and arithmetic functions.

Number Theory

Large Numbers

In programming, when a number is too large to fit in built-in data types like long long int, we refer to it as a large number or big integer.

Doubling a Large Number

We go through each digit in the number (from right to left), double it, and keep track of any carry to the next digit. After we’re done, we reverse the result to get the final answer.

Key Steps:

  • Start from the last digit (rightmost).
  • Multiply the digit by 2 and add any carry from the previous step.
  • Store the result’s last digit and carry over the rest.
  • After the loop, if there is a remaining carry, append it.
  • Reverse the final string to get the correct result.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
string doubleBigNumber(const string& num) {
    string result = "";
    int carry = 0;

    for (int i = num.size() - 1; i >= 0; --i) {
        int digit = num[i] - '0';
        int doubled = digit * 2 + carry;
        carry = doubled / 10;
        result += (doubled % 10) + '0';
    }

    if (carry) result += carry + '0';
    reverse(result.begin(), result.end());
    return result;
}
This post is licensed under CC BY 4.0 by the author.