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:
- GCD of two numbers when one of them can be very large
- LCM of two large numbers
- Sum of two large numbers
- Divisible by 37 for large numbers
- Difference of two large numbers
- Remainder with 7 for large numbers
- Sort an array of large numbers
- Large Fibonacci Numbers in Java
- Find Last Digit of a^b for Large Numbers
- Writing power function for large numbers
- Multiply Large Numbers represented as Strings
- Modulo power for large numbers represented as strings
- Java Program for Sum of squares of first n natural numbers
- Java Program for cube sum of first n natural numbers
- Multiply large integers under large modulo
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.