Perfect cube, full cube formula
/* A3 = b3 + c3 + d3 is the perfect cubic equation. For example, 123 = 63 + 83 + 103.
Write a program to search for all the tuples (a, B, c, d) for the positive integer N (N ≤ 100) given by any operator ),
Make a3 = b3 + c3 + d3, where 1 <a, B, c, d ≤ N.
Input
Positive integer N (N ≤ 100)
Output
Each row outputs a perfect cube, which is output in ascending order according to the value of. When the values of a in two perfect cubic equations are the same
, The output is arranged in non-descending ascending order according to B, c, and d, that is, the first output with a small value of B, the first output with a small value of c, and then the first output with a small value of d.
Sample Input
24
Sample output
Cube = 6, Triple = (3, 4, 5)
Cube = 12, Triple = (6, 8, 10)
Cube = 18, Triple = (2, 12, 16)
Cube = 18, Triple = (9, 12, 15)
Cube = 19, Triple = (3, 10, 18)
Cube = 20, Triple = (7, 14, 17)
Cube = 24, Triple = (12, 16, 20)
*/
/*
# Include <stdio. h>
# Include <math. h>
Int main ()
{
Int I, n, x, y, z;
Do
{
Scanf ("% d", & n );
} While (n <0 | n> 100 );
For (I = 2; I <= n; I ++)
{
For (x = 1; x <= n; x ++)
For (y = x + 1; y <= n; y ++)
For (z = y + 1; z <= n; z ++)
If (pow (I, 3) = pow (x, 3) + pow (y, 3) + pow (z, 3 ))
{
Printf ("Cube = % d, Triple = (% d, % d, % d)", I, x, y, z );
Printf ("\ n ");
}
}
Return 0;
}
*/
Optimized Code
# Include <stdio. h>
# Include <math. h>
Int main ()
{
Int cube [101];
Int n, I, a, B, c, d;
Scanf ("% d", & n );
For (I = 1; I <= n; I ++)
Cube [I] = pow (I, 3 );
For (a = 6; a <= n; a ++)
For (B = 2; B <= A-2; B ++) // when B = 1, other values that meet the conditions cannot be found. Sequential values of B, c, d can be obtained first,
// If c is set to B + 1, and d is set to B + 2, then B + 2 <a, then the satisfied value may be obtained.
{
If (cube [a] <cube [B] + cube [B + 1] + cube [B + 2])
Break; // If cube [a] is smaller than the cube value corresponding to consecutive B, c, and d, it is not likely to meet
// The cube values of non-consecutive B, c, and d Exit the loop.
For (c = B + 1; c <A-1; c ++)
{
If (cube [a] <cube [B] + cube [c] + cube [c + 1])
Break; // when B is relatively fixed, the value of cube [a] is smaller than the cube value corresponding to the continuous c. d.
// That is, it cannot satisfy non-consecutive c, and the cube value corresponding to d exits the loop.
For (d = c + 1; d <n; d ++)
If (cube [a] = cube [B] + cube [c] + cube [d]) // when cube [a] is greater than continuous B, c, when d corresponds to the cube value,
// C is relatively fixed. Find the corresponding d one by one
Printf ("Cube = % d, Triple = (% d, % d, % d) \ n", a, B, c, d );
}
}
Return 0;
}