简体   繁体   中英

How would you solve this problem using recursion and without other looping methods?

The function below returns multiples of 2 between num1 / num2. So in case where num 1 = 8, num 2 = 12, it will return 3 as such multiples equal to 8, 10, 12. How would you duplicate this function using recursion only?

function makeMultiplesOfDigit(num1, num2) {
  let count = 0;
  let start = num1;
  let end = num2;

  if (num1 > num2) {
    start = num2;
    end = num1;
  }

  if (start === 0) {
    start = 1;
  }

  for (let i = start; i <= end; i++) {
    if (i % 2 === 0) {
      count += 1;
    }
  }

  return count;
}

Recursion is not really the right method to this problem, as there is a closed formula for this, but here you go:

 function makeMultiplesOfDigit(num1, num2) { if (num1 > num2) return makeMultiplesOfDigit(num2, num1); let isEven = 1 - num1 % 2; if (num1 == num2) return isEven; // base case return isEven + makeMultiplesOfDigit(num1 + 1, num2); } // demo console.log(makeMultiplesOfDigit(8, 12));

Note: your code does not count 0 as an even number when num1 is 0, which is strange: surely 0 is an even number. And if the function were called with (-1, 1), then it would still count 0 as even, so it is not consistent either.

As an additional information, here is the closed formula version:

 function makeMultiplesOfDigit(num1, num2) { return ((Math.abs(num1 - num2) + 1) >> 1) + (num1 % 2 === 0 && num2 % 2 === 0); } // demo console.log(makeMultiplesOfDigit(8, 12));

function makeMultiplesOfDigit(num1,num2,count=0){
        if (num1 % 2 === 0 ){
            count++
         }
        if(num1>=num2){
            return count
         }
        else{
           count = makeMultiplesOfDigit(num1+1,num2,count)
           return count
         }
      }
  

    makeMultiplesOfDigit(8, 12)


    

Saw a similar response, anyway, here you go.

 function getMultiplesInRange(num1, num2, num3 = 0) { if (num1 > num2) return num3 const val = num1 % 2 === 0 ? 1 : 0 return getMultiplesInRange(num1 + 1, num2, val + num3) } console.log(getMultiplesInRange(8, 12))

If you are only dealing with a situation where the first number is smaller than the second number:

// Generic utils
const isEven = (n) => n % 2 === 0 
const eq = (a, b) => a === b
const inc = (n) => n + 1
const add = (a, b) => a + b

// Constants
const incCount = 1
const leaveCount = 0

// Implementation
const shouldIncCount = (n) => isEven(n) ? incCount : leaveCount
const makeMultiplesOfDigit = (a, b) => eq(a, b) ? shouldIncCount(a) : add(shouldIncCount(a), makeMultiplesOfDigit(inc(a), b));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM