The fact that your coefficients are integers doesn't mean that the roots are. (Up to two of them may actually be complex, as in the example that I gave.)
...
Unless, of course, your original question (which you aren't telling us) actually says more; e.g. that the particular cubics being considered DO have equal real roots, in which case at least one of them would also be a root of the quadratic formed from differentiating the cubic.
There's a cubic equation Ax^3+Bx^2+Cx+D=0
Find the roots that are integers [-1000;1000].
Input: integers A,B,C,D [-3000;3000]
Output: sort the roots in ascending way, separate them with symbol "_". Roots that are equal have to be printed only once.
#include <iostream>
usingnamespace std;
int main()
{
constint N = 3;
int coeff[N+1];
constint xmin = -1000, xmax = 1000;
cout << "Input coefficients, starting with highest power of X: ";
for ( int p = N; p >= 0; p-- ) cin >> coeff[p];
int numRoots = 0;
for( int x = xmin; x <= xmax; x++)
{
int result = coeff[N];
for ( int p = N - 1; p >= 0; p-- ) result = result * x + coeff[p];
if ( result == 0 )
{
if ( numRoots > 0 ) cout << "_";
numRoots++;
cout << x;
if ( numRoots == N ) break;
}
}
}
Input coefficients, starting with highest power of X: 1 -1 1 -1
1
Input coefficients, starting with highest power of X: 1 -1 -1 1
-1_1
Input coefficients, starting with highest power of X: 1 -6 11 -6
1_2_3
Are you past calc 1? If so, you can take the dx of this function easily (3*A*x*x + 2*B*x = C) and maybe code up a simple newtons method off that?
Brute force works too, but what do you do when that approach is not useful?
You don't have to do anything more here, but I am tossing some ideas out so you have some thoughts for next time.