samedi 30 décembre 2017

Breaking inline for loop on condition

I want to find the first number k such that the sum of squares of all naturals up to that number is divisible by 200.

Normal solution:

sum = 0
for k in range(1, max+1):
    sum += k**2
    if sum % 200 == 0:
        return k

I have a one-liner:

print(sum([i^2 for i in range(1, 1000)]))

But I want to break this loop as soon as this sum is divisible by 200.

Is it possible to do this?

Aucun commentaire:

Enregistrer un commentaire