Check whether a series of operations yields a given number with JavaScript Recursion

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 25-Aug-2020 07:37:25
Advertisements