abishek kumaresan - 2 years ago 315

Python Question

`sum = 0`

x = 2**32

for i in range(x):

sum=sum+i;

print sum

I am getting a

`MemoryError`

`2**32`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

For a brute-force approach, try this:

```
x = sum(i for i in xrange(2**32))
```

The above will be more efficient, as it uses `xrange`

to generate the numbers lazily, and it also uses a generator expression with `sum()`

to avoid generating temporary data that gets discarded immediately.

But that will still take some time, as `2**32`

is a big number. The smart way to solve this problem is to use a formula, as suggested by @DeepSpace:

```
n = 2**32 - 1
x = (n * (n + 1)) / 2
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**