/*---------------------------------------------------------------------------
File name: Square_3digits.cpp
Author: HJin
Created on: 6/27/2007 02:23:03
Environment: Windows XP Professional SP2 English +
Visual Studio 2005 v8.0.50727.762
Modification history:
Analysis:
Do a brute force search for all th 9! permutations of 1..9.
We want to search a permuatation of 1..9 (stored in a[0..8])
so that
(a_0 a_1 a_2)^2 = (a_3 a_4 a_5 a_6 a_7 a_8).
Sample output:
567 * 567 = 321489
854 * 854 = 729316
Press any key to continue . . .
*/
#include <iostream>
#include <algorithm>
using namespace std;
int a[9];
void search();
int main(int argc, char** argv)
{
search();
return 0;
}
void search()
{
int n_3digits;
int n_6digits;
int i;
for(i=0; i<9; ++i)
{
a[i] = i+1;
}
// the first case 1 2 3 4 5 6 7 8 9 is omitted.
while(next_permutation(a, a+9))
{
n_3digits = 10* (10*a[0] + a[1]) + a[2];
n_6digits = 0;
for(i=3; i<9; ++i)
{
n_6digits = 10 * n_6digits + a[i]; // Horn's rule
}
if(n_3digits * n_3digits == n_6digits)
{
for(i=0; i<3; ++i)
cout<<a[i];
cout<<" * ";
for(i=0; i<3; ++i)
cout<<a[i];
cout<<" = ";
for(i=3; i<9; ++i)
cout<<a[i];
cout<<endl;
}
}
}