We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Easy sum
You are viewing a single comment's thread. Return to all comments →
Gauss's summation implemented in Python.
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
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,