2

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?

EDIT

I've seen this Q&A on break list comprehension but it breaks when a value inside the list fulfills some requirement. I want to break when the sum of all values that have been iterated over, reaches some requirement.

Alec
  • 1,986
  • 4
  • 23
  • 47
  • Possible duplicate of [break list comprehension](https://stackoverflow.com/questions/9572833/break-list-comprehension) – Stephen Rauch Dec 30 '17 at 22:57
  • @StephenRauch - There may be something there, but it only shows how to break on a condition relating to each value inside the list. I want to break once the *sum* of these has reached a certain point. – Alec Dec 30 '17 at 23:05
  • Possible duplicate of [Stopping a Reduce() operation mid way. Functional way of doing partial running sum](https://stackoverflow.com/questions/3130352/stopping-a-reduce-operation-mid-way-functional-way-of-doing-partial-running-s) – hansaplast Dec 30 '17 at 23:15

0 Answers0