I came across this simple question: A entry level math question for kids,
A, B, C and D are 1-digit number from 0 to 9, find all possibilities for the following multiplication:
A B C D X 9 --------- D C B A
If you are a programmer, you probably think that this is too easy, it can be solved almost instantly by brute-forcing all numbers, four nested loops with each number from 0 to 9 (the most naive solution) will be good. Alternatively, you can loop a single number from 0 to 9999 and check the result (multiplied by 9) to see if it is exactly the reverse (a bit more complicated).
The straightforward C++ implementation prints two answers: 0000 * 9 = 0000 and 1089 * 9 = 9801.
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 | // helloacm.com #include <iostream> using namespace std; int main() { for (int a = 0; a < 10; a ++) { for (int b = 0; b < 10; b ++) { for (int c = 0; c < 10; c ++) { for (int d = 0; d < 10; d ++) { int n1 = a * 1000 + b * 100 + c * 10 + d; int n2 = d * 1000 + c * 100 + b * 10 + a; if (n1 * 9 == n2) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; cout << "d = " << d << endl; } } } } } return 0; } |
// helloacm.com #include <iostream> using namespace std; int main() { for (int a = 0; a < 10; a ++) { for (int b = 0; b < 10; b ++) { for (int c = 0; c < 10; c ++) { for (int d = 0; d < 10; d ++) { int n1 = a * 1000 + b * 100 + c * 10 + d; int n2 = d * 1000 + c * 100 + b * 10 + a; if (n1 * 9 == n2) { cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl; cout << "d = " << d << endl; } } } } } return 0; }
Wait, you don’t need computer to find this at all! The 0000 is very obvious but how about the other solution?
A can only be 1 (if it is 2 or greater, D is two digit)
D then is 9
B then is 0 (the case of 1 can be excluded easily)
and C is 8
so the answer is 1089, faster than the computer.
–EOF (The Ultimate Computing & Technology Blog) —
loading...
Last Post: Using Resharper - Turning to LINQ
Next Post: Learning Powershell - Recursive Fibonacci Computation