Search code examples
c++divide-and-conquer

C++ Divide and conquer algorithm problems


I have just learnt about Divide and Conquer algorithm and I'm a little bit confused about it. The question is my homework, I have tried many ways to fix my code but it did not run.

#include <iostream>
using namespace std;

void inputArray(int* a, int& n)
{
    cout << "Input n:";
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cout << "input a[" << i << "]= ";
        cin >> a[i];
    }
}

int sumeven(int* a, int l, int r)
{
    if (l == r  && a[l] % 2 == 0)
    {
        return a[l];
    }

    int mid = (l + r) / 2;
    int s1 = sumeven(a, l, mid);
    int s2 = sumeven(a, mid + 1, r);
    return s1 + s2;

}

int main()
{
    int n;
    int a[20];
    inputArray(a, n);
    cout<<sumeven(a, 0,n-1);
    return 0;
}

Solution

  • Try to test your programs without user input first:

    #include <iostream>
    using namespace std;
    int sumeven(int* a, int l, int r)
    {
        if (r >= 6) return 0;
        if (l > r ) return 0;
        if (l >= r)
        {
            if (a[l] % 2 == 0)
            {
                return a[l];
            }
            else
            {
                return 0;
            }
        }
    
        int mid = (l + r) / 2;
        int s1 = sumeven(a, l, mid);
        int s2 = sumeven(a, mid + 1, r);
        return s1 + s2;
    
    }
    int main()
    {
        int n=6;
        int a[6]={1,2,3,48,5,6};
        cout<<sumeven(a,0,n-1);
        return 0;
    }