1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
|
#include <iostream>
#include <string>
#include <stdio.h>
#include <cmath>
using namespace std;
double a, b, c, A, B, C, A2, ans1, ans2, ansgcd, q, t, x1, x2, answer;
char title[] = "Factor Trinomials";
char equation[] = "ax^2 + bx + c";
char Exit = 'y';
void centerstring(char* string)
{
int l = strlen(string);
int pos = (int)((80 - l) / 2);
for (int i = 0; i < pos; i++)
cout << " ";
cout << string;
}
int gcd( int a, int b )
{
c = 0;
while(1)
{
a = a % b;
if( a == 0 )
return b;
b = b % a;
if( b == 0 )
return a;
}
}
double square_root(double t)
{
q = t / 2;
while (1)
{
answer = 0.5*(q + (t / q));
if (q == answer)
return answer;
q = answer;
}
}
int main()
{
while (Exit == 'y' || Exit == 'Y')
{
centerstring(title);
cout << "\n";
centerstring(equation);
cout << "\nA = ";
cin >> A;
cout << "B = ";
cin >> B;
cout << "C = ";
cin >> C;
ans1 = B - square_root( (B * B) - (4 * A * C));
ans2 = B + square_root( (B * B) - (4 * A * C));
A = A * 2;
A2 = A;
ansgcd = gcd(A, ans1);
if (ansgcd < 0)
{
A = A / -ansgcd;
ans1 = ans1 / -ansgcd;
}
else
{
A = A / ansgcd;
ans1 = ans1 / ansgcd;
}
ansgcd = gcd(A2, ans2);
if (ansgcd < 0)
{
A2 = A2 / -ansgcd;
ans2 = ans2 / -ansgcd;
}
else
{
A2 = A2 / ansgcd;
ans2 = ans2 / ansgcd;
}
cout << "\nAnswer is:\n(";
if (A == 1.0)
cout << "x";
else
cout << A << "x";
if (ans1 < 0)
cout << " - " << -ans1;
else
cout << " + " << ans1;
cout << ")(";
if (A2 == 1.0)
cout << "x";
else
cout << A2 << "x";
if (ans2 < 0)
cout << " - " << -ans2;
else
cout << " + " << ans2;
cout << ")";
x1 = -ans1 / A;
x2 = -ans2 / A2;
cout << "\nX = " << x1 << " or " << x2;
do
{
cout << "\n\nFactor another? [y/n] ";
cin >> Exit;
} while (!Exit == 'n' && !Exit == 'N' && !Exit == 'y' && !Exit == 'Y');
cout << "\x1b[2J\x1b[H" << flush;
}
return 0;
}
|