- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements