Sum of first N natural numbers when N is extremely large
Given a positive integer n, the task is to find the sum of the first n natural numbers given that n is very large (1 ≤ n ≤ 1020000).
Input: n = 4
1 + 2 + 3 + 4 = 10
Input: n = 12345678910
Approach: Sum of first n natural numbers is (n * (n + 1)) / 2 but given that n can be extremely large (1 ≤ n ≤ 1020000). Now its obvious that we can only store the sum in a string. A simple solution is to run a loop till n and calculate the sum by the method of addition of two strings and iteratively add all numbers one by one but time complexity of this solution will be very large.
We can optimise this solution using BigInteger class in java. BigInteger class gives pre-defined methods for Mathematical operations which can be used to solve (n * (n + 1)) / 2 to calculate the required result.
- Take a string for holding the value of extremely large input.
- Transform this string to a BigInteger.
- Calculate (n * (n + 1)) / 2 using BigInteger class’s pre-defined methods.
- Print the calculated sum in the end.
Below is the implementation of the above approach: