I have a small problem that I can’t solve.
I would like, with a JavaScript code, to decompose an integer, such as the sum of several integers greater than zero and different from each other.
For now, I have managed to create the code below.
The problem is that it generates integers greater than zero, which however can be equal to each other.
How can I make them different from each other?
JavaScript code
const targetNumber = 40;
const numTerms = 20;
const result = BreakDownNumber(targetNumber, numTerms);
console.log("number to break down:", targetNumber);
console.log("random numbers:", result);
function BreakDownNumber(targetNumber, numTerms) {
let numbers = [];
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
let sum = 0;
for (let i = 0; i < numTerms - 1; i++) {
let randomNumber = getRandomNumber(1, targetNumber - sum - (numTerms - i - 1));
numbers.push(randomNumber);
sum += randomNumber;
}
// Last number
numbers.push(targetNumber - sum);
return numbers;
}
I probably have to change everything, but I don’t know.
I know it’s a trivial question but I’m truly a beginner. 😉
I gladly accept any advice and help.
Thanks a lot to everyone.
Happy programming!
2
Answers
You can use a while loop to generate a random number, and if it does not conform to the rules do not increment i
Note:
the last number cannot mathematically conform to your rules if you have random numbers, it’s just up to chance + the last number goes 1 over the numTerms (I left it like that in case it was intentional)
(I changed the numbers to make it run quicker)
The smallest sum of n different positive integers is 1+2+…+n = n(n+1)/2. So for a given n, if the target is smaller than that, there is no solution.
Otherwise, one valid solution is 1, 2, …, n-1, (target – n).