I am trying to find a solution to this task “Determine how many integers, starting from the number 1, need to be added so that the sum will equal more than 100.”using JavaScript. I have my solution but I tend to feel that it is wrong. Could you please help me?
I do not even realize if I understand the task in the right way. Please see my solution below:
<script>
let result = 0;
for ( i = 1; i<20; i++){
result+=i;
if( result>100) {
break
}
}
console.log(i)
</script>
Output is 14, It is right , but I am not sure in the way I solving it.
Advertisement
Answer
If it works, there is nothing wrong about it.
You could simplify it, for example use a while rather than a for loop :
let total = 0
let count = 1;
// we loop until total is greater or equals to 100.
while(total < 100) {
// add the current count to the total
total += count;
// increment the count.
count++;
}
// we need to account for the last ++;
console.log(count - 1);Here the while loop will run until the condition is broken.