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).
Examples:
Input: n = 4
Output: 10
1 + 2 + 3 + 4 = 10Input: n = 12345678910
Output: 76207893880582233505
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:
Java
// Java program to find the sum of the first n // natural numbers when n is very large import java.math.BigInteger; class GeeksForGeeks { // Function to return the sum of first // n natural numbers static BigInteger sum(String n) { // b1 = 1 BigInteger b1 = BigInteger.ONE; // b2 = 2 BigInteger b2 = new BigInteger( "2" ); // Converting n to BigInteger BigInteger bigInt = new BigInteger(n); // Calculating (n * (n + 1)) / 2 BigInteger result = (bigInt.multiply(bigInt.add(b1))).divide(b2); return result; } // Driver code public static void main(String[] args) throws java.lang.Exception { String n = "12345678910" ; System.out.println(sum(n)); } } |
Python3
# Python3 program to find the sum # of first n natural numbers when # n is very large # Function to return the sum of # first n natural numbers def Sum (n): result = (n * (n + 1 )) / / 2 return result # Driver Code if __name__ = = "__main__" : n = "12345678910" print ( Sum ( int (n))) # This code is contributed # by Rituraj_Jain |
PHP
<?php // PHP program to find the sum // of first n natural numbers when // n is very large // Function to return the sum of // first n natural numbers function Sum( $n ) { $result = ( $n * (int)(( $n + 1)) / 2); return $result ; } // Driver Code $n = "12345678910" ; echo Sum( $n ); // This code is contributed // by Akanksha Rai ?> |
76207893880582233505