- 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
Check whether a series of operations yields a given number with JavaScript Recursion
By starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of new numbers can be produced. We are required to write a function that, given a number, tries to find a sequence of such additions and multiplications that produce that number. And returns a boolean based on the fact whether or not there exists any such sequence
For example,
The number 13 could be reached by first multiplying by 3 and then adding 5 twice, so the function should return true for 13. Whereas the number 15 cannot be reached at all, so the function should return false for 15.
Approach
We will use a recursive approach, where we repeatedly try all possibilities that lead to the desired solution. The code for this approach will be −
Example
const sequenceExists = (num, curr = 1) => { if(curr > num){ return false; }; if(curr === num){ return true; }; return sequenceExists(num, curr+5) || sequenceExists(num, curr*3); }; console.log(sequenceExists(18)); console.log(sequenceExists(15)); console.log(sequenceExists(32)); console.log(sequenceExists(167)); console.log(sequenceExists(17)); console.log(sequenceExists(1119));
Output
The output in the console will be −
true false true true false true