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:
- LCM of two large numbers
- Sum of two large numbers
- GCD of two numbers when one of them can be very large
- Remainder with 7 for large numbers
- Divisible by 37 for large numbers
- Difference of two large numbers
- Large Fibonacci Numbers in Java
- Sort an array of large numbers
- Find Last Digit of a^b for Large Numbers
- How to generate Large Prime numbers for RSA Algorithm
- Fermat's Factorization method for large numbers
- Factorial of Large numbers using Logarithmic identity
- Writing power function for large numbers
- Multiply Large Numbers represented as Strings
- Print all K digit repeating numbers in a very large number
- 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
- Find (a^b)%m where 'a' is very large
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.