Finding nth element of an increasing sequence using JavaScript


Problem

Consider an increasing sequence which is defined as follows −

  • The number seq(0) = 1 is the first one in seq.
  • For each x in seq, then y = 2 * x + 1 and z = 3 * x + 1 must be in seq too.
  • There are no other numbers in seq.

Therefore, the first few terms of this sequence will be −

[1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]

We are required to write a function that takes in a number n and returns the nth term of this sequence.

Example

Following is the code −

 Live Demo

const num = 10;
const findNth = n => {
   let seq = [1], x = 0, y = 0
   for (let i = 0; i < n; i++) {
      let nextX = 2 * seq[x] + 1, nextY = 3 * seq[y] + 1
      if (nextX <= nextY) {
         seq.push(nextX)
         x++
         if (nextX == nextY)
            y++
         } else {
            seq.push(nextY)
            y++
      }
   }
   return seq[n];
}
console.log(findNth(num));

Output

22

Updated on: 17-Apr-2021

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements