
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 −
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
- Related Articles
- Finding nth element of the Padovan sequence using JavaScript
- Finding the nth element of the lucas number sequence in JavaScript
- Finding the sum of all numbers in the nth row of an increasing triangle using JavaScript
- Finding nth digit of natural numbers sequence in JavaScript
- Finding the nth power of array element present at nth index using JavaScript
- Finding Fibonacci sequence in an array using JavaScript
- Finding sum of every nth element of array in JavaScript
- Finding the only out of sequence number from an array using JavaScript
- Strictly increasing sequence JavaScript
- JavaScript: Check if array has an almost increasing sequence
- Finding sum of sequence upto a specified accuracy using JavaScript
- Finding the nth missing number from an array JavaScript
- Finding the longest non-negative sum sequence using JavaScript
- Finding the majority element of an array JavaScript
- Finding the nth digit of natural numbers JavaScript

Advertisements