While browsing the Raspberry Pi forums the other day, I came across a thread called “Potentially useful things to program” which reminded me of a problem I solved when I was first becoming interested in programming. The code I wrote to solve the problem wasn’t a particularly useful thing to program, as in the Raspberry Pi forums thread, but rather it was the first code that really demonstrated the usefulness of programming to me.
The problem I had was:
Solve: (a^2)b-c = abc Conditions: -10 <= A,B,C <= 10 A,B,C != 0
And the solution was found by way of brute force with a simple set of nested for loops. Trivial really, but at the time I was very pleased with myself for it was the first time I’d solved something faster and more easily using code rather than pen and paper. The original code was written for Matlab but I’ve recreated the program in C++ below.
#include <iostream> using namespace std; int main() { int startVal = -10; int endVal = 10; for(int A = startVal; A <= endVal; A++) { for(int B = startVal; B <= endVal; B++) { for(int C = startVal; C <= endVal; C++) { int LHS = (A*A*B)-C; int RHS = A*B*C; if(LHS == RHS) { if(A != 0 && B != 0 && C != 0){ cout << "Solution found: A = " << A << ", t B = " << B << ", t C = " << C << "n"; } } } } } return 0; }
And the solution…
Solution found: A = -2, B = 1, C = -4 Solution found: A = -1, B = 2, C = -2 Solution found: A = 1, B = -2, C = 2 Solution found: A = 2, B = -1, C = 4