Calculating value of a sequence based on some input using JavaScript

Problem

We need to write a JavaScript function that takes a number n as input and calculates the value of a sequence term un. Given a sequence where:

u<sub>1</sub> = 0 and u<sub>2</sub> = 2

Our function should find the value of un for which the following recurrence relation holds:

6u<sub>n</sub>u<sub>n+1</sub> - 5u<sub>n</sub>u<sub>n+2</sub> + u<sub>n+1</sub>u<sub>n+2</sub> = 0

Understanding the Sequence

From the recurrence relation, we can derive that this sequence follows the pattern un = 2n-1 for n ? 2, and u1 = 0.

Example Implementation

Here's the JavaScript function to calculate the sequence value:

const num = 13;

const sequenceSum = (num = 1) => {
    if (num === 1) {
        return 0;  // u1 = 0
    }
    const res = Math.pow(2, num - 1);
    return res;
};

console.log(`u${num} = ${sequenceSum(num)}`);
console.log(`u1 = ${sequenceSum(1)}`);
console.log(`u2 = ${sequenceSum(2)}`);
console.log(`u3 = ${sequenceSum(3)}`);

Output

u13 = 4096
u1 = 0
u2 = 2
u3 = 4

How the Formula Works

The sequence follows this pattern:

  • u1 = 0 (given initial condition)
  • u2 = 2 = 21 (given initial condition)
  • un = 2n-1 for n ? 2

Alternative Implementation

You can also use bit shifting for better performance with powers of 2:

const sequenceValue = (n) => {
    if (n === 1) return 0;
    return 1 << (n - 1);  // Equivalent to 2^(n-1)
};

console.log(`Using bit shift - u10 = ${sequenceValue(10)}`);
console.log(`Using Math.pow - u10 = ${Math.pow(2, 10 - 1)}`);
Using bit shift - u10 = 512
Using Math.pow - u10 = 512

Conclusion

This sequence problem demonstrates how recurrence relations can be solved to find closed-form expressions. The key insight is recognizing that un = 2n-1 for n ? 2, with the special case u1 = 0.

Updated on: 2026-03-15T23:19:00+05:30

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements