
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Nth Term of Arithmetic Progression (AP) in JavaScript
To find the nth term of an arithmetic progression in JavaScript, we need to write a function that will calculate the nth term. In this article, we will explore how to find the nth term of an AP using JavaScript.
We are required to write a JavaScript function that takes in three numbers as arguments (the first two numbers are supposed to be the starting two consecutive terms of an arithmetic progression). And the third number, say n, is the 1 index-based element of the series whose value we must calculate.
If the input is 2, 5, 7
Then the series will be:
2, 5, 8, 11, 14, 17, 20
And the output should be 20.
Understanding Arithmetic Progression (AP)
Arithmetic Progression (AP) is a sequence of numbers in which the difference between any two consecutive terms remains constant. An Arithmetic Progression (AP) follows the general formula:
nth term = a + (n-1) * d
where:
- a = First term of the AP
- d = Common difference between consecutive terms
- n = Position of the term to find
Implementation Steps
To achieve this, follow the steps mentioned below:
- Initialize Variables: Define the first term a = 2, the second term b = 5, and the required term position N = 7.
- Define the Function: The function takes three parameters: first (first term), second (second term), and num (position of the term to find).
- Calculate the Common Difference: Compute the difference between the second and first terms.
- Calculate the Factor: Calculate the factor using the formula (num - 1) * diff.
- Find the Nth Term: Then, add the calculated factor to the first term
- Return the Result: The function returns the computed nth term.
Example
The following is an example of finding nth term of an arithmetic progression that is following the above steps:
const a = 2, b = 5; const N = 7; const findNthTerm = (first, second, num) => { const diff = second - first; const fact = (num - 1) * diff; const term = first + fact; return term; }; console.log(findNthTerm(a, b, N));
Output
20
Conclusion
In this article, we have created a function that finds the nth term of an arithmetic progression using a simple formula. This is the simple way to find the nth term. By understanding and using this formula in JavaScript, developers can easily solve many problems that involve sequences.