C++ Program to add few large numbers

C++Server Side ProgrammingProgramming

Suppose we have an array nums of some large numbers. The large numbers are in range (-2^31 to 2^31 - 1). We have to find the sum of these numbers.

So, if the input is like nums = [5000000003, 3000000005, 8000000007, 2000000009, 7000000011], then the output will be 25000000035.

To solve this, we will follow these steps −

  • x := 0
  • for initialize i := 0, when i < size of nums, update (increase i by 1), do −
    • x := x + nums[i]
  • return x

Example

Let us see the following implementation to get better understanding

#include <iostream>
#include <vector>
using namespace std;

long long int solve(vector<long long int> nums){
   long long int x = 0;

   for(int i=0; i<nums.size(); i++){
      x = x + nums[i];
   }
   return x;
}
int main(){
   vector<long long int> nums = {5000000003, 3000000005, 8000000007, 2000000009, 7000000011};
   cout << solve(nums);
}

Input

{5000000003, 3000000005, 8000000007, 2000000009, 7000000011}

Output

25000000035
raja
Published on 12-Oct-2021 09:24:14
Advertisements