Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 (1 × 3 = 3, 3 + 5 = 8, 8 + 5 = 13), 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 recursive function checks two paths at each step:
- Add 5 to the current number
- Multiply the current number by 3
The recursion stops when we either reach the target number (return true) or exceed it (return false).
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));
true false true true false true
How It Works
The function uses two base cases:
- curr > num: If current value exceeds target, this path is impossible
- curr === num: If current value equals target, we found a valid sequence
For the recursive case, it explores both operations using the logical OR operator. If either path returns true, the entire expression returns true.
Tracing Example: sequenceExists(13)
// Starting from 1, find sequence to reach 13
console.log("Path 1: 1 × 3 = 3, then 3 + 5 = 8, then 8 + 5 = 13");
console.log("sequenceExists(13):", sequenceExists(13));
Path 1: 1 × 3 = 3, then 3 + 5 = 8, then 8 + 5 = 13 sequenceExists(13): true
Conclusion
This recursive solution efficiently explores all possible sequences of adding 5 or multiplying by 3. The function returns true if any valid sequence exists to reach the target number, demonstrating the power of recursion in exploring multiple solution paths.
