• + 0 comments

    Gauss's summation implemented in Python.

    def solve(n, m):
        return ((m-1)*m//2)*(n//m)+(n%m)*(n%m+1)//2
    

    Explanation: Gauss's formula for summation states that the sum from 1 to N for any natural number, N, can be calculated arithmetically:

    The problem statement implies an approach where one would loop from 1 up to n, taking mod m at each step.
    However, with some out-of-the-box thinking, by applying the mod m ahead of time, you will see that in fact we are summing from 1 to m-1 over and over.
    The number of times we take this sum is equal to

    This means we can apply Gauss's formula to sum 1 to m-1:
    to get this preliminary value, and multiply the result by num_loops.
    If m divides n, this will be the result to return.
    However, if a remainder exists from the previous division, then there are a few more integers to add to the total. Simply apply Gauss's formula one more time,
    and add this to our total to be returned.