xxxxxxxxxx
38
// This is a short program that I'm using to introduce for loops.
// factorial with for loop...
// start with while loop
// comment it out (keep it for comparison purposes)
// below the comment, refactor the program as a for loop
// exercise: termial with for loop vs closed formula
let sum = 0;
let n = 10 ** 8;
for (let k = 1; k <= n; k++) {
sum += k;
}
// on my machine, the for loop breaks at n = 10 ** 9
// (it runs for a while, then returns the wrong answer)
console.log(sum);
console.log(n * (n + 1) / 2);
/* Bonus exercise:
Determine the precise threshold where the termial breaks! Can use a variation
of the bisection method that we introduced, called binary search.
The difference is that we're searching a discrete range of values, like 1000, 1001,
10002..., 10 **9 rather than a continuous range of values, like the decimal numbers
between 0 and 1.
If multiple people try this, we'll have a collective experiment to see if the
result depends on the computer that's running the code!
Note to self:
I should do this myself, in case there are any hints I want to provide
(I could provide them in a separate file), and to make sure the concepts that
are used are all things we've covered so far. Also, would this work? The problem
is that when a value is too big, it'll break the function...
*/