Faulty Algorithm?

Alex wants to create an algorithm to calculate the sum of the first 100 positive integers.

He tells the algorithm to
1. Create the variable sum with an initial value of 0.
2. Start with the value of i = 1 i = 1
3. Add i i to the sum
4. Add 1 to i i
5. Continue doing so till i = 100 i = 100

Does this algorithm work?

No, it should sum till i = 101 i = 101 . No, it should sum till i = 99 i = 99 . No, it should add 2 to i i . Yes it works perfectly.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Brock Brown
Jun 19, 2015

Alex's algorithm will only sum the first 99 99 positive integers. The part where i i is added to sum is located before the part where 1 1 is added to i i , so the loop ends before it gets a chance to add 100 100 to sum .

And of course, here is some Python:

Python 3.4:

1
2
3
4
5
6
7
# Alex's algorithm
sum = 0
i = 1
while i != 100:
    sum += i
    i += 1
print("i =", i)

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...