Search code examples
javascriptnode.jsjavascript-objects

get all 3 digit number whose sum is 11 or we can say module is 1 in JS


In response I want all 3 digit numbers whose sum is 11 and also gives module 1 and also want to know how can I push 000 in array in js.

For example number = 128, sum = 11 and module(remainder) = 1. Like this I want all that numbers in array. Can anyone share the logic for the same.

Thanx in advance.


Solution

  • I'm not sure what the second check is supposed to be (the modulus of something has to be 1). If that is supposed to be that the modulus of all digits of the number has to be 1, here is how you could do it:

    var results = [];
    for (let i = 1; i < 10; i++) {
      for (let j = 0; j < 10; j++) {
        for (let k = 0; k < 10; k++) {
          if (i + j + k === 11 && i % j % k === 1) {
            results.push(i.toString() + j.toString() + k.toString());
          }
        }
      }
    }
    
    console.log(results);

    OR:

    var results = [];
    for (let i = 100; i < 1000; i++) {
      const [one, two, three] = i.toString().split('').map(i => +i);
      if (one + two + three === 11 && one % two % three === 1) {
        results.push(i.toString());
      }
    }
    
    console.log(results);

    Basically just go through all the possible combination and do the checks on each number.