Algorithm
problem link- https://www.spoj.com/problems/MADODDSUM/
MADODDSUM - Easy Odd Sum
Hablu likes odd numbers a lot. So he wants the sum of all odd numbers in range [a, b]. That is, find the sum of all odd numbers i such that (a ≤ i ≤ b). Seems easy right? Because it is.
Input
The first and only line will contain 2 integers a, b where (0 ≤ a ≤ 108) and (0 ≤ b ≤ 108).
Output
In one line, output the value of the sum
Example
Input: 0 9 Output: 25
Code Examples
#1 Code Example with Python Programming
Code -
Python Programming
def get(n):
n = (n + 1) // 2
return n * n
a, b = map(int, input().split())
if a % 2 == 1:
a -= 1
print(get(b) - get(a))
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <cstdarg>
#include <utility>
#include <cctype>
#include <cstdio>
#include <vector>
#include <string>
#include <cmath>
#include <ctime>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <map>
using namespace std;
typedef long long LL;
typedef vector<int> vint;
typedef pair<int,int> pint;
typedef unsigned long long ULL;
short CC_;
#define sf scanf
#define pf printf
#define NL pf("\n");
#define dcc (double)
#define PP getchar();
#define SS printf(">_<LOOOOOK@MEEEEEEEEEEEEEEE<<( %d )>>\n",++CC_);
#define DD(x_) cout<<">>>>( "<<++CC_<<" ) "<<#x_<<": "<<x_<<endl;
#define EXT(st_) cout<<"\n>>>Exicution Time: "<<(double)(clock()-st_)/CLOCKS_PER_SEC<<endl;
//constants
const int SZ= 1E6;
const int INF= (1<<29);
const double EPS= 1E-9;
const double PI= 2*acos(0.0);
void solve(void)
{
ULL a,b;
cin>>a>>b;
if(a%2 == 0) a++;
if(b%2 == 0) b--;
int n= (b - a)/2 +1;
LL sum= (n* (2*a + (n-1)*2))/2;
cout<< sum <<endl;
}
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
}
Copy The Code &
Try With Live Editor
Input
Output
Demonstration
SPOJ Solution-Easy Odd Sum-Solution in C, C++, Java, Python