Algorithm Analysis
If we calculate the sum using a loop, in the worst case (when , ) we would have to perform up to iterations, which would lead to Time Limit Exceeded. Let's use the formula for the sum of an arithmetic progression. The first term equals , the last term equals , and the total number of terms is . Then, the desired sum equals
It should also be noted that the resulting sum may not fit in an int
type. Therefore, we should use the long long
type for calculation.
Algorithm Implementation
Read the input data. Calculate and output the answer.
scanf("%lld %lld", &a, &b); res = (a + b) * (b - a + 1) / 2; printf("%lld\n", res);
Java Implementation
import java.util.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); long a = con.nextLong(); long b = con.nextLong(); long res = (a + b) * (b - a + 1) / 2; System.out.println(res); } }
Python Implementation
a, b = map(int, input().split()) res = (a + b) * (b - a + 1) // 2 print(res)