-
Some optimizations step by step:
Code:
for (a=2; a<=x; a++)
{
for (b=2; b<=x; b++)
{
if ((x>2) && ((x%2)==0) && (a<=b) && (a+b==x))
{
cout << a << " and " << b << endl;
}
}
}
The red condition is unnecessary, since the input has already been verified. When it comes to the orange test, it can be moved to the inner loop's condition:
Code:
for (b=2; b<=x; b++)
{
for (a=2; a<=b; a++)
{
if (a+b==x)
{
cout << a << " and " << b << endl;
}
}
}
Note that I reordered the loops, now the 'b' is outer.
Going this way you can do what iMalc said eliminating the last condition.
Given 'a' in set: <2..b> there can be only one (or zero) 'a', such that (a + b = x), and this is (a = x - b):
Code:
for (b=2; b<=x; b++)
{
cout << x - b << " and " << b << endl;
}
If (b == x) then (a == 0), if (b == x - 1) then (a == 1). Both 0 and 1 are not primes:
Code:
for (b=2; b < x - 1; b++)
{
cout << x - b << " and " << b << endl;
}
The code is much cleaner now, I think you will manage to implement IsPrime function. Just in case you get stuck:
Code:
for (b=2; b < x - 1; b++)
{
if (IsPrime(b) && IsPrime(x - b))
{
cout << x - b << " and " << b << endl;
}
}