JavaScript code to find nth term of a series - Arithmetic Progression (AP)

To find the nth term of an arithmetic progression in JavaScript, we need to write a function that calculates the nth term using the AP formula. 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 three parameters: the first two consecutive terms of an arithmetic progression, and the position n of the term we want to find.

If the input is 2, 5, 7 (first term = 2, second term = 5, position = 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 where the difference between any two consecutive terms remains constant. This constant difference is called the common difference (d).

The formula for the nth term of an AP is:

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 find the nth term of an AP, follow these steps:

  • Calculate Common Difference: Find d = second term - first term
  • Apply the Formula: Use nth term = first + (n-1) × d
  • Return Result: Return the calculated nth term

Example: Basic Implementation

const findNthTerm = (first, second, num) => {
    const diff = second - first;
    const factor = (num - 1) * diff;
    const nthTerm = first + factor;
    return nthTerm;
};

// Test with example
const a = 2, b = 5, N = 7;
console.log(`The ${N}th term is: ${findNthTerm(a, b, N)}`);

// Additional test cases
console.log(`3rd term: ${findNthTerm(2, 5, 3)}`);
console.log(`5th term: ${findNthTerm(2, 5, 5)}`);
The 7th term is: 20
3rd term: 8
5th term: 14

Optimized Version

Here's a more concise version of the function:

const findNthTermAP = (first, second, n) => {
    return first + (n - 1) * (second - first);
};

// Generate series for visualization
const generateAPSeries = (first, second, count) => {
    const series = [];
    const diff = second - first;
    for (let i = 1; i 

Series: 2, 5, 8, 11, 14, 17, 20
7th term: 20

Practical Example with Validation

function findAPTerm(first, second, position) {
    // Input validation
    if (position 

First term: 3
Common difference: 4
10th term: 39
39
---
First term: 10
Common difference: 5
6th term: 35
35

Conclusion

Finding the nth term of an arithmetic progression in JavaScript is straightforward using the formula: nth term = a + (n-1) × d. This approach efficiently calculates any term in the sequence without generating all preceding terms.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements