-
[C++]Trinomial Factoring
This short code allows you to enter B and C in a trinomial and then outputs it in factored form, and gives you the solutions.
Note: this only works if a = 1
(ax^2 + Bx + C)
Example:
Enter B: 7
Enter C: 10
Factored Form: (x+5)(x+2)
Solutions: x=-5, x=-2
Code:
#include<iostream.h>
#include<vector>
using namespace std;
int check(vector<int> vec, int b, int c)
{
for(vector<int>::iterator x = vec.begin(); x!=vec.end(); x++)
{
for(vector<int>::iterator y = vec.end() - 1; y!=vec.begin(); y--)
{
if((*x + *y) == b && (*x)*(*y)== c)
{
cout<<"Factored form is: "<<"(x ";
if(*x>0)
cout<<"+ "<<*x<<")(x ";
else
cout<<*x<<")(x ";
if(*y>0)
cout<<"+ "<<*y<<")";
else
cout<<*y<<") ";
cout<<endl<<"Solutions: "<<"x = "<<-1*(*x)<<", x = "<<-1*(*y);
return 1;
}
}
}
cout<<"This problem can't be solved. No factors of C add up to B"<<endl;
return 0;
}
int main()
{
vector<int> vec;
int b, c;
cout<<"This can solve equations in the following format:"<<endl;
cout<<"x^2 + Bx + C "<<endl;
cout<<"Enter B: ";
cin>>b;
cout<<"Enter C: ";
cin>>c;
for(int a = c * -1; a<c; a++)
{
if(c%a == 0)
{
vec.push_back(a);
}
if(a==(-1))//to make it skip zero.
a++;
}
check(vec, b, c);
cin.get();
cin.get();
return 0;
}