Chinaunix首页 | 论坛 | 博客
  • 博客访问: 215604
  • 博文数量: 68
  • 博客积分: 3120
  • 博客等级: 中校
  • 技术积分: 715
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-08 09:53
文章分类
文章存档

2012年(29)

2011年(3)

2010年(18)

2009年(18)

我的朋友

分类: C/C++

2012-02-05 13:59:02

问题:

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;
}


阅读(1055) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~