Project Euler:Problem 32 Pandigital products

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.

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.


#include <iostream>
#include <map>
using namespace std;

bool pand(int a, int b, int c)
{
	map<int, int>mp;
	int tmp[] = { a, b, c };
	int num = 1;
	if (b != 0)
		num = 3;
	for (int i = 0; i < num; i++)
	{
		int p = tmp[i];
		while (p)
		{
			if (mp[p % 10] != 0)
				return false;
			else
			{
				mp[p % 10] = 1;
				p = p / 10;
			}
		}
	}
	if (mp[0] != 0)
		return false;
	if (b == 0)         //说明a中无反复
		return true;
	int count = 0;
	for (int i = 1; i <= 9; i++)
	{
		if (mp[i] != 0)
			count++;
	}
	if (count == 9)
		return true;
	else
		return false;
}


int main()
{
	map<int, int>mp;
	for (int i = 1; i <= 9876; i++)
	{
		if (pand(i,0,0))
		{
			for (int j = 1; j < i; j++)
			{
				if (i*j <= 10000)
				{
					if (pand(i, j, i*j))
						mp[i*j] = 1;
				}
			}
		}
	}
	map<int, int>::iterator iter;
	int res = 0;
	for (iter = mp.begin(); iter != mp.end(); iter++)
	{
		if (mp[iter->first] == 1)
			res += iter->first;
	}
	cout << res << endl;
	system("pause");
	return 0;
}


posted @ 2017-08-14 10:07  yangykaifa  阅读(229)  评论(0编辑  收藏  举报