fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int divideEtImpera(int arr[], int lo, int hi) {
  6.  
  7. int m;
  8.  
  9. if(lo == hi) {
  10.  
  11. return arr[ lo ];
  12.  
  13. } else {
  14.  
  15. int x, y;
  16. m = (lo + hi) >> 1;
  17. x = divideEtImpera(arr, lo, m);
  18. y = divideEtImpera(arr, m + 1, hi);
  19. if(x < y) return x + y;
  20. else
  21. return y + x;
  22.  
  23. }
  24. }
  25.  
  26. void comb(int x, int y, int &z) {
  27. z = x + y;
  28. }
  29. void sumN(int arr[], int left, int right, int &z) {
  30. int x1, x2;
  31. if(left == right) {
  32. z = arr[left];
  33. } else {
  34. int m = (left + right) >> 1;
  35. sumN(arr, left, m, x1);
  36. sumN(arr, m + 1, right, x2);
  37. comb(x1,x2,z);
  38. }
  39.  
  40. };
  41.  
  42. int main(int argc, char const *argv[]) {
  43.  
  44. int arr[] = {1,2,3,4,5,6,7,8,9,10},
  45. sum,
  46. n = sizeof(arr)/sizeof(arr[0]),
  47. z;
  48.  
  49. cout<<"Sum 1 + 2 + 3 +...+ 10 = ";
  50. sum = divideEtImpera(arr, 0, n - 1);
  51. cout<<sum;
  52. cout<<endl;
  53. cout<<"Sum 1 + 2 + 3 +...+ 10 = ";
  54. sumN(arr, 0, n - 1, z);
  55. cout<<z;
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0s 5440KB
stdin
Standard input is empty
stdout
Sum 1 + 2 + 3 +...+ 10 = 55
Sum 1 + 2 + 3 +...+ 10 = 55