No, that number is not correct. The problem with your code is this line:
total = total-y
Here, you decrease total
further and further with each value of y
that you try, never resetting it to the value after just subtracting x
. To fix it, create a new variable, e.g. total2
, and use that in the inner loop.
total2 = total-y
This way, you get 498501
combinations. Also, you can break
from the inner loop as soon as total2 < 0
.
If you need just the number of combinations: Note that there are N-1
combinations to sum two numbers to N
, e.g. for N==4
: 1+3
, 2+2
, 3+1
(assuming you consider 1+3
and 3+1
different). You can extend this to the case of three numbers as partitioning the number in two parts two times. This way, you only need a single loop. And this can be simplified further to an O(1) formula.
Example, with naive approach using product
as reference:
>>> N = 100 # to make reference faster
>>> sum(1 for t in product(range(1, N+1), repeat=3) if sum(t)==N)
4851
>>> sum(N-1-i for i in range(1, N-1))
4851
>>> ((N-2)*(N-1))//2
4851
Of course, also works for N = 1000
(or much, much larger):
>>> N = 1000
>>> sum(N-1-i for i in range(1, N-1))
498501
>>> ((N-2)*(N-1))//2
498501