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 free
d pointers; the memory they point to is invalid.