![]() |
Arithmetic progression is a sequence of numbers in which the difference between any two consecutive terms is always equal. This difference between any two consecutive terms is known as a common difference and it can be positive, negative, or zero. Below are the approaches to find Sum of n terms in Arithmetic Progression: Table of Content Using Iterative ApproachIn this approach, we will use a loop to iterate over each term of A.P. from the first term to the nth term. Inside the loop, we will calculate each term of A.P. using the formula a + i × d, where a is the first term of A.P. i is the index of the current term, and d is the common difference of A.P. and add it to current sum. Example: The below code implements the iterative approach by using the for loop to find the sum of the AP series.
Output Sum of the first 20 terms using Iterative approach 670 Time Complexity: O(n) , as we are using loop Space Complexity: O(1) , constant space Using Recursive ApproachIn this approach, we will define a recursive function. This function stops when the number of term equal to 1 , it will return first term of A.P. If n is greater than 1, then recursively call itself to calculate sum of the first n terms. Example: The below code uses a recursive function which calls itself to fins the sum of n terms AP series.
Output Sum of the first 15 terms using Recursive approach is 750 Time Complexity: O(n), as function make recursive call n times. Space Complexity: O(n), n recursive calls are made. Using Direct FormulaThe sum of n terms of A.P. in mathematics can be calculated directly using the formula. In this approch, we will implement the same formula to calculate the sum. Syntax:Sn = ((n/2) * (2*a + (n-1) * d) ) where, Sn is sum of n terms of A.P., n is number of terms of A.P., a is first term of given A.P., d is common difference of A.P. Example: The below code implements the mathematical formula to calculate the sum of the n terms of AP series.
Output Sum of first 10 terms of AP with first term 2 and common difference 2 is : 110 Time Complexity : O(1) , constant time Space Complexity : O(1) , constant space Using three-pointer techniqueThe three-pointer technique finds common elements in three sorted arrays by initializing pointers, comparing current elements, adding matches to the result, and moving the smallest pointer until all arrays are traversed, ensuring an efficient search. Example:
Output [ 20, 80 ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |