Program adds 2 fractions and displays their sum in a reduced form (n times). Could someone help me optimize my solution (According to SPOJ, the time limit has been exceeded)
My solution:
#include <iostream>
using namespace std;
int main()
{
int n, a, b, c, d, gcd;
long long num, den;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a >> b >> c >> d;
num = (a*d)+(b*c);
den = b*d;
for(int j = 1; j <= num && j <= den; ++j)
{
if(num % j == 0 && den % j == 0)
{
gcd = j;
}
}
cout << num/gcd << " " << den/gcd << endl;
}
}