How many pairs (i, j) exist such that 1 <= i <= j <= n, j - i <= a?
'n' and 'a' input numbers.
The problem is my algorithm is too slow when increasing 'n' or 'a'.
I cannot think of a correct algorithm.
Execution time must be less than 10 seconds.
Tests:
n = 3
a = 1
Number of pairs = 5n = 5
a = 4
Number of pairs = 15n = 10
a = 5
Number of pairs = 45n = 100
a = 0
Number of pairs = 100n = 1000000
a = 333333
Number of pairs = 277778388889n = 100000
a = 555555
Number of pairs = 5000050000n = 1000000
a = 1000000
Number of pairs = 500000500000n = 998999
a = 400000
Number of pairs = 319600398999n = 898982
a = 40000
Number of pairs = 35160158982
n, a = input().split()
i = 1
j = 1
answer = 0
while True:
if n >= j:
if a >= (j-i):
answer += 1
j += 1
else:
i += 1
j = i
if j > n:
break
else:
i += 1
j = i
if j > n:
break
print(answer)