-1

I'm having a difficult time figuring out how'd I'd accomplish a task and am looking for help.

So, I need to use a function that'll find a pair of numbers (to be allocated dynamically) that meets a condition and returns a pointer to it.

Here's what I have:

int* f_cubes_sum(int n)
{
    //Declaring array
    int *numSet;
    numSet = (int *)malloc(2); // Only two because I'm looking for a pair
    //Declaring variables
    int sum = 0;
    int a = 0;
    int b = 0;
    bool results = false;



    while (b < n && results == false)
    {
        while (a < n)
        {
            sum = a^3 + b^3;
            if (sum == n)
            {
                results = true;
            }
            else
            {
                a = a + 1;
            }

            sum = 0;
        }

        if (results = false)
        {
            a = 0;
            b = b + 1;
        }
    }

    if (results = false)
    {
        a = NULL;
        b = NULL;

    }

    numSet[0] = a;
    numSet[1] = b;
    free(numSet);
    return numSet;
}

And in my main function, how would I access both numbers?

Thank you for your time

Ryan L
  • 1
  • 1
  • 1
    `malloc(2)` allocates 2 bytes; you need `malloc(2 * sizeof(*numSet))`. But if you need 2 ints locally, why not use an automatic array? – M Oehm Nov 15 '15 at 20:06
  • 1
    You can't free the allocated memory, and then return a pointer to it! – Thomas Padron-McCarthy Nov 15 '15 at 20:07
  • 1
    For a start, `main` can't use the memory block if you already freed it. – user253751 Nov 15 '15 at 20:07
  • 1
    Not sure if this is causing your problem cause I barely read it, but in C, `=` is assignment, not equality. You need to replace your `if (something = something)` with `if (something == something)`. Rookie mistake ;) – Luke Joshua Park Nov 15 '15 at 20:07
  • Does anyone know what's up with everyone casting `malloc`'s result in C? This is often done by complete beginners which suggests they're taught to do that by their professors... OP, FYI: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605994 – user4520 Nov 15 '15 at 20:08
  • Oh, and `a^3` isn't the cube of `a`. That's `a*a*a`. ( `^` is the xor or exclusive or operator in C.) – M Oehm Nov 15 '15 at 20:09
  • 2
    This starts to feel like an exam. "Find the ten errors in the code. You get one point for each error you have found." – Thomas Padron-McCarthy Nov 15 '15 at 20:10
  • @szczurcio There are two professors at my university that do this. I think a lot of people who started with C++ just assume C++ is a superset of C. It makes me cringe a little, since there's not stdlib.h included. I hope that was in the actual code. – Bobby Sacamano Nov 15 '15 at 20:25
  • Just so you know, comments like `declaring variables` and `declaring array` aren't useful in the slightest; your comments should describe what the function does at a high level. `a = a + 1;` is equivalent to `a++` or `a += 1`. You don't have to compare a boolean against false, you can just do `if (!result)`. – Bobby Sacamano Nov 15 '15 at 20:29
  • For the particular case of returning two numbers, [returning them in a struct](http://stackoverflow.com/a/25381839/841108) may be much more efficient – Basile Starynkevitch Nov 16 '15 at 06:06

1 Answers1

3

You are looking for a function that determines whether a number can be written a the sum of two cubes and if so, it should yield the two numbers whose cubes are summed. Basically you need:

  • an information on whether n can be written as a³ + b³ and
  • if so, the values of a and b.

You can use your approach of allocating an array of two integers and return that on success and NULL on failure. If you do so, you should allocate the array only if you have a result:

int *f_cubes_sum(int n)
{
    int a, b;

    // logic to work out whether a³ + b³ == n
    if (a*a*a + b*b*b == sum) {
        int *res = malloc(2 * sizeof(*res));

        res[0] = a;
        res[1] = b;

        return res;
    }

    // no solution found
    return NULL;
}

The drawback here is that the calling code has to free the returned pointer:

int *res = f_cubes_sum(2778);

if (res) {
    printf("%d, %d\n", res[0], res[1]);
    free(res);
}

Another approach is to pass in an array that your code has to fill and indicate success or failure with a boolean return value:

bool f_cubes_sum(int n, int res[2])
{
    int a, b;

    // logic to work out whether a³ + b³ == n
    if (a*a*a + b*b*b == sum) {
        res[0] = a;
        res[1] = b;

        return true;
    }

    // no solution found
    return false;
}

Now the calling code has to provide the space for the result:

int res[2];

if (f_cubes_sum(2778, res)) {
    printf("%d, %d\n", res[0], res[1]);
}

Of course, because you are always dealing with two possible result values, you could also pass pointers to these values instead of passing an array. Here's a variant of your function that does this:

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

bool f_cubes_sum(int n, int *pa, int *pb)
{
    int a = 0;

    while (1)
    {
        int a3 = a*a*a;

        if (a3 > n) break;

        int b = cbrt(n - a3) + 0.5;
        int b3 = b*b*b;

        if (a3 + b3 == n) {
            *pa = a;
            *pb = b;
            return true;
        }

        a++;
    }

    return false;
}

int main(void)
{
    int a, b;
    int n = 35001;

    if (f_cubes_sum(n, &a, &b)) {
        printf("%d^3 + %d^3 == %d\n", a, b, n);
    } else {
        printf("Nothing found for %d.\n", n);
    }

    return 0;
}

Also note what commenters have alreadey pointed out:

  • In C, = assigns, == compares. Unfortunately, an assignment inside an iF condition is valid C: It will assign the value and then test it, entering the clause if it isn't 0 or false. Therefore if (x = false) never enters the if clause. Switch on warnings to carch such mistakes.

  • The ^ operator isn't the power operator, it is the bitwise xor operator. Raising a number a to the power of b is done with the floating-point function pow(a, b). If the exponent is a known small integer, it is usually better to write the multiplication explicitly. Thus, pow(a, 3) is rendered better as a*a*a.

  • When allocating memory, be sure the make enough room for the desired type. Also don't use freed pointers; the memory they point to is invalid.

M Oehm
  • 28,726
  • 3
  • 31
  • 42
  • Looks like a stray formatting issue in 3rd paragraph from bottom (the *antepenultimate* paragraph - for Leffler's benefit) – David C. Rankin Nov 15 '15 at 21:13
  • Oh, yes, those pesky backwards quotes. I usually manage go have one or two leaning the wrong way. And thanks for correcting the function call. – M Oehm Nov 16 '15 at 06:03