Hello,
For a exercism challenge I need to calculate the total
grains on a
chessboard.
So I did :
atSquare: anInteger
�������� self validateInput: anInteger.
�������� ^ anInteger = 1
�������� ������ ifTrue: [ 1 ]
�������� ������ ifFalse: [ 2 * (self atSquare: anInteger - 1) ]
but when I run the tests , the vm seems to be not responsive
for some 4
- 5 seconds.
Is there a way I can use this code and take care that the vm
stays
responsive.
What do you want the VM to do in addition to calculating
that sum while it is calculating that sum?
The best way to keep the VM responsive is to take a page
from Gauss' notebook and pay attention to the numbers[1].
Let's consider the first four squares and extrapolate from
there.
In binary, the squares hold the following grains: 2r1,
2r10, r2100, and 2r1000. When we add them up, we get 2r1111.
If we use Gauss' tricks, we can notice that 2r1111 is equal
to 2r10000 - 1. So, the sum of the grains on the first 4
squares is 2^5 - 1. You can easily generalize that pattern,
of course. Then your program can calculate the answer
quickly.
[1] The story goes that Gauss' teacher was frustrated
with his student's abilities and set him a challenge to
occupy him for some time: sum the numbers from 1 through
100. Gauss immediately answered 5,050, much to his teacher's
chagrin.
Regards,
Roelof