find the result from the number selected and sum until o find your extra number

Viewed 24

enter 2 positive numbers. then control all numbers between the two first numbers. each number is added within itself and is equal to the third number. The third number must never be greater than 10

exemple 1 number 1 in: 35 number 2 in: 50 number 3 in: 10

result: 37, 46

exemple 2 number 1 in: 1 number 2 in: 50 number 3 in: 8

result: 8,17,26,35,44

let getal1 = (prompt("Geef een getal 1 in:"));
let getal2 = (prompt("Geef een getal 2 in:"));
let getal3 = Number(prompt("Geef een getal 3 (niet meer dan 10) in:"));

let resultaat = "";
for (let i = getal1; i <= getal2; i++) {
  resultaat = resultaat + i + ",";
}
console.log(resultaat.substring(0, resultaat.length - 1));

let arr = Array(resultaat);

for (let x = 1; x <= arr; x++) {
  if (arr === getal3) {
    console.log(arr)
  } else {

  }

}

for know i just do dit, but i no have idea i i get sum the number between commas. can i use your help?

1 Answers

I think you should really work on your question description (if it's because of the language barrier maybe you could write them in your native language and use google translate)

So if I understand correctly you have 3 inputs:

  • start: number
  • end: number
  • targetSum: number

And your goal is to get the list of numbers between start and end which match the following criteria: the sums of its digits should be equal to targetSum.

const getal1 = 2;
const getal2 = 50;
const getal3 = 8;

const solution = solve(getal1, getal2, getal3);
console.log(solution); // logs the solution array
console.log(solution.join(','); // logs the solution as a string with each number separated by a comma

function solve(start, end, targetSum) {
  const results = [];
  for (let i = start; i <= end; i++) {
    // if the sum of the digits is equal to target sum, the number is added to the result list
    if (sumDigits(i) === targetSum) {
      results.push(i);
    }
  }
  return results;
}

// utils to sum the digits of a number
function sumDigits(num) {
  let result = 0;
  // loop as long as num is different from 0
  while (num) {
    result += num % 10; // get the last digit and add it to the result
    num = Math.floor(num / 10); // update num by removing the last digit
  }
  return result;
}

Related