Algorithm
problem link- https://www.spoj.com/problems/PRADIPSUM/
PRADIPSUM - Easy Math
Zoro is a student of a primary school. He likes to solve mathematical problem. One day he tries to solve a math, but he is unable to solve the problem efficiently because of being a student of primary school. As you are a programmer he wants your help to solve this problem. The problem is to find the sum of some consecutive numbers.
Example, if the first number is 2 and the last number is 5, then the result would be
2 + 3 + 4 + 5 = 14
Input
Every line contains two integers a and b. Input is terminated by the end of file.
Output
Output the sum the of all numbers between a and b (inclusively).
Constraints
-108 ≤ (a , b) ≤ 108
Example
Input: 2 5 5 10 Output: 14 45
Code Examples
#1 Code Example with Python Programming
Code -
Python Programming
def sum(x):
if x < 0:
return -(-x * (-x + 1) // 2)
else:
return x * (x + 1) // 2
while True:
try:
a, b = map(int, input().split())
if a > b:
a, b = b, a
if b < 0:
print(sum(a) - sum(b + 1))
elif a <= 0:
print(sum(b) + sum(a))
else:
print(sum(b) - sum(a - 1))
except EOFError:
exit(0)
Copy The Code &
Try With Live Editor
Input
5 10
Output
45
Demonstration
SPOJ Solution-Easy Math-Solution in C, C++, Java, Python