#include <iostream>
using namespace std;
int divideEtImpera(int arr[], int lo, int hi) {
int m;
if(lo == hi) {
return arr[ lo ];
} else {
int x, y;
m = (lo + hi) >> 1;
x = divideEtImpera(arr, lo, m);
y = divideEtImpera(arr, m + 1, hi);
if(x < y) return x + y;
else
return y + x;
}
}
void comb(int x, int y, int &z) {
z = x + y;
}
void sumN(int arr[], int left, int right, int &z) {
int x1, x2;
if(left == right) {
z = arr[left];
} else {
int m = (left + right) >> 1;
sumN(arr, left, m, x1);
sumN(arr, m + 1, right, x2);
comb(x1,x2,z);
}
};
int main(int argc, char const *argv[]) {
int arr[] = {1,2,3,4,5,6,7,8,9,10},
sum,
n = sizeof(arr)/sizeof(arr[0]),
z;
cout<<"Sum 1 + 2 + 3 +...+ 10 = ";
sum = divideEtImpera(arr, 0, n - 1);
cout<<sum;
cout<<endl;
cout<<"Sum 1 + 2 + 3 +...+ 10 = ";
sumN(arr, 0, n - 1, z);
cout<<z;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCBkaXZpZGVFdEltcGVyYShpbnQgYXJyW10sIGludCBsbywgaW50IGhpKSB7CgogICAgIGludCBtOwoKICAgICBpZihsbyA9PSBoaSkgewoKICAgICAgICByZXR1cm4gYXJyWyBsbyBdOwoKICAgICB9ICBlbHNlIHsKCiAgICAgICAgaW50IHgsIHk7CiAgICAgICAgbSA9IChsbyArIGhpKSA+PiAxOwogICAgICAgIHggPSBkaXZpZGVFdEltcGVyYShhcnIsIGxvLCBtKTsKICAgICAgICB5ID0gZGl2aWRlRXRJbXBlcmEoYXJyLCBtICsgMSwgaGkpOwogICAgICAgIGlmKHggPCB5KSByZXR1cm4geCArIHk7CiAgICAgICAgICAgICAgZWxzZQogICAgICAgICAgICAgICAgICByZXR1cm4geSArIHg7CgogICAgIH0KfQoKdm9pZCBjb21iKGludCB4LCBpbnQgeSwgaW50ICZ6KSB7CiAgICAgeiA9IHggKyB5Owp9CnZvaWQgc3VtTihpbnQgYXJyW10sIGludCBsZWZ0LCBpbnQgcmlnaHQsIGludCAmeikgewogICAgICBpbnQgeDEsIHgyOwogICAgICBpZihsZWZ0ID09IHJpZ2h0KSB7CiAgICAgICAgIHogPSBhcnJbbGVmdF07CiAgICAgIH0gZWxzZSB7CiAgICAgICAgaW50IG0gPSAobGVmdCArIHJpZ2h0KSA+PiAxOwogICAgICAgIHN1bU4oYXJyLCBsZWZ0LCBtLCB4MSk7CiAgICAgICAgc3VtTihhcnIsIG0gKyAxLCByaWdodCwgeDIpOwogICAgICAgIGNvbWIoeDEseDIseik7CiAgICAgIH0KCn07CgppbnQgbWFpbihpbnQgYXJnYywgY2hhciBjb25zdCAqYXJndltdKSB7CgogIGludCBhcnJbXSA9IHsxLDIsMyw0LDUsNiw3LDgsOSwxMH0sCiAgICAgIHN1bSwKICAgICAgbiA9IHNpemVvZihhcnIpL3NpemVvZihhcnJbMF0pLAogICAgICB6OwoKICBjb3V0PDwiU3VtIDEgKyAyICsgMyArLi4uKyAxMCA9ICI7CiAgc3VtID0gZGl2aWRlRXRJbXBlcmEoYXJyLCAwLCBuIC0gMSk7CiAgY291dDw8c3VtOwogIGNvdXQ8PGVuZGw7CiAgY291dDw8IlN1bSAxICsgMiArIDMgKy4uLisgMTAgPSAiOwogIHN1bU4oYXJyLCAwLCBuIC0gMSwgeik7CiAgY291dDw8ejsKICByZXR1cm4gMDsKfQo=