In this video, we will see a C++ program for the sum of first n natural numbers.
Examples:
1. Input : n = 7
Output : 28
Explanation :
Note that: 1 + 2 + 3 + 4 + 5 + 6 + 7= 28
2.Input : 8
Output : 36
Explanation :
Note that: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
In this video, we see two different approaches for the Sum of first n natural numbers in C++:
1. By using for loop
2. Using Mathematical formula: I.e [ Sum of first n natural numbers = (n*(n+1))/2]
Apart from that, we will see the Time and Space complexity of both the approaches as follows:
- Using For loop:
Time Complexity O(n)
Space complexity O(1)
- Using Mathematical formula:
Time Complexity O(1)
Space complexity O(1)
Find if the given number is the sum of the first n natural numbers: https://www.geeksforgeeks.org/find-given-number-sum-first-n-natural-numbers/
Program to find sum of first n natural numbers: https://www.geeksforgeeks.org/program-find-sum-first-n-natural-numbers/