Last active
October 6, 2021 13:56
-
-
Save Ranzeplay/5254821f1b2e410efa1dd0e8c36959eb to your computer and use it in GitHub Desktop.
Big number calculation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| std::string add(std::string augend, std::string addend) | |
| { | |
| // Reverse two numbers, make them 0-index aligned | |
| std::reverse(augend.begin(), augend.end()); | |
| std::reverse(addend.begin(), addend.end()); | |
| std::string result; | |
| auto max_length = std::max(augend.size(), addend.size()); | |
| // To mark if there's a carry | |
| bool x_flag = false; | |
| size_t index; | |
| for (index = 0; index < max_length; index++) | |
| { | |
| // Add x_flag is to add if there's a carry in calculation of previous digit | |
| short ta = index < augend.size() ? augend[index] - '0' : 0; | |
| short tb = index < addend.size() ? addend[index] - '0' : 0; | |
| short single_digit_result = ta + tb + x_flag; | |
| x_flag = false; | |
| if (single_digit_result >= 10) | |
| { | |
| x_flag = true; | |
| single_digit_result -= 10; | |
| } | |
| result += single_digit_result + '0'; | |
| } | |
| // Add carry flag | |
| if (x_flag) result += '1'; | |
| std::reverse(result.begin(), result.end()); | |
| return result; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| std::string multiply(std::string multiplier, std::string multiplicand) | |
| { | |
| // reverse multiplicand and multiplier, make them 0-index aligned | |
| // Make them easier to calculate | |
| std::reverse(multiplier.begin(), multiplier.end()); | |
| std::reverse(multiplicand.begin(), multiplicand.end()); | |
| std::string result = "0"; | |
| size_t offset = 0; | |
| for (auto mpd_digit: multiplicand) | |
| { | |
| size_t t_offset = 0; | |
| std::string current_iteration_result; | |
| for (auto mlp_digit: multiplier) | |
| { | |
| int current_digit_result = (mpd_digit - '0') * (mlp_digit - '0'); | |
| auto t_str = number_to_string(current_digit_result); | |
| t_str += std::string(t_offset, '0'); | |
| t_offset++; | |
| current_iteration_result = add(current_iteration_result, t_str); | |
| } | |
| current_iteration_result += std::string(offset, '0'); | |
| offset++; | |
| result = add(result, current_iteration_result); | |
| } | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment