What is the output of this code snippet?
Do you know the following story of the brilliant mathematician Carl Friedrich Gauss? When 8-year old Gauss went to school, his math teacher sought a few minutes of breathing pause. He told his class to solve the problem of adding all subsequent numbers from 1-100:
But as little Gauss promptly reported the solution, the short pause was over before it began.
Surprised (and a bit grumpy as the story goes), the teacher asked the boy how he had come up with a solution so quickly. Gauss explained his simple solution. He organized the sequence into pairs of numbers each summing up to 101:
1+100,2+99,3+98,...,50+51. There are 50 such pairs, so the total result was
Yet, the modern-time little Gauss would be even lazier. He would type the following one-liner into his mobile Python app: sum(range(1,101)).
The range function returns a sequence starting from the first value (inclusive) and ending in the second value (exclusive).
The sum function sums up the values of this sequence. Combining both functions sums up the sequence from 1-100—faster than the brilliant Carl Friedrich Gauss.
Are you a master coder?
Test your skills now!