mercredi 26 octobre 2016

Sum of two squares decomposition counting

I want to count how many pairs of natural number there are such that a2 + b2 = c2. As an input to my function I have c.

My idea was to first check whether the condition is fulfilled, than if not, I wanted to have a loop iterating desired expression up to c. If result is equal to the square of c than I wanted to have count++. Question is why this is not working?

Some corrections added.

int sum(int c) {
    int b=1;
    int a=1;
    int count=0;
    int result;

    if (a*a + b*b != c*c)
    {
        for (int i=1; i<=c; i++)
        {
            b=i;
            result = a*a + b*b;
            if (result == c*c)
                count++;
        }
        a++;
    }
    else
        count++;

    return count;
}

The problem is I still do not understand why this does not want to work.

My second idea was to approach it with while loop:

int sum(int c) {
    int b=1;
    int a=1;
    int count=0;
    int result;

    if (a*a + b*b != c*c)
    {
        while(b<=c)
        {
            result = a*a + b*b;
            if (result == c*c)
                {count++;
                b++;
                }
                else
                    b++;
        }
        a++;
    }
    else
        count++;

    return count;
}

Not working as well.

Anybody any ideas as to how to make it work? Any of those two versions? Maybe hints?

Aucun commentaire:

Enregistrer un commentaire