# Integral roots of a cubic equation in C++

In this tutorial, we will learn how to find the integral roots of a cubic equation in C++.

#### Cubic equation

Cubic equation is of the form— ** ax ^{3 }+ bx^{2 }+ cx + d = 0.**

a , b , c , d are real numbers and a is non zero.

The root of an equation is a real number that satisfies the equation.

A cubic equation has 3 roots, some of which can be equal.

These roots may not be integers always.

Let the three roots be p, q, r, then they satisfy the following:

*p + q + r = -b/a**p q + q r + r p = c/a**p q r = – d/a*

**Examples**:

*2x ^{3 }– 4x^{2 }– 22x + 24 = 0*

*a=2 b=-4 c=-22 d=24*

Root of the equations are- -3 , 1 and 4.

### Integral roots of a cubic equation C++ code

To find the integral roots of a cubic equation, we will start by talking value x = 0, and check if it satisfies the equation.

If the value of x satisfies the equation, it is a root of the equation, and after that, we decrement the value of x by 1.

Break from the loop if the value of the solution by putting the current value of x becomes less than zero.

Now, we have all the negative integral roots of the equation, and we will repeat the above procedure for the positive roots of the equation.

Start with x = 1, and check if it satisfies the equation.

We will increment the value of x by 1, every time and we will break from the loop when the value of the solution by putting the current value of x becomes greater than zero.

#include<bits/stdc++.h> using namespace std; int main(){ int a=2 , b=-4 , c=-22 , d=24; int x=0; while(true){ int curr = a * pow(x , 3) + b * pow(x , 2) + c * x + d; if(curr==0) cout<<x<<" "; x--; if(curr<0) break; } x=1; while(true){ int curr = a * pow(x , 3) + b * pow(x , 2) + c * x + d; if(curr==0) cout<<x<<" "; x++; if(curr>0) break; } }

OUTPUT

-3 1 4

You may also read:

C++ program to find solutions of a quadratic equation

Find the root of an equation using Newton Raphson method in C++

## Leave a Reply