We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
答案:45228
#include
#include
#include
using namespace std;
int toInt(const int *a, int len)
{
int i=0;
int result=0;
for (i=0; i result = result*10 + a[i];
return result;
}
int main(void)
{
int a[]={1,2,3,4,5,6,7,8,9};
int sum = 0;
set s;
int m=0,n=0,p=0;
do{
//Case 1: 1 4 4
m = toInt(a, 1);
n = toInt(a+1, 4);
p = toInt(a+5, 4);
if (p == m*n) s.insert(p);
//Case 2: 2 3 4
m = toInt(a, 2);
n = toInt(a+2, 3);
p = toInt(a+5, 4);
if (p == m*n) s.insert(p);
//Case 3: 3 2 4
m = toInt(a, 3);
n = toInt(a+3, 2);
p = toInt(a+5, 4);
if (p == m*n) s.insert(p);
//Case 4: 4 1 4
m = toInt(a, 4);
n = toInt(a+4, 1);
p = toInt(a+5, 4);
if (p == m*n) s.insert(p);
}while( next_permutation(a, a+9) );
set::iterator it;
for (it = s.begin(); it != s.end(); it++)
sum += *it;
printf("%d\n", sum);
return 0;
}