Project Euler 78 : Coin partitions

Project Euler 78 : Coin partitions

Integer Partition

Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so p(5)=7.

| OOOOO |
| OOOO O |
| OOO OO |
| OOO O O |
| OO OO O |
| OO O O O |
| O O O O O |

Find the least value of n for which p(n) is divisible by one million.

既然题目都告诉了是coin partitions,那么直接按照分硬币的思路做肯定没问题,至于硬币如何分,参见硬币划分

题目的意思就是任意面值的硬币咯,也就是用1~n的硬币来划分n。哈哈直接套用以前的结论,验证题目中的p(5)=7 ,5块钱用1,2,3,4,5来分,那么应该是1(1x)(1x2)(1x3)(1x4)(1x5)x5 的系数,唔,展开即可。

什么你问我怎么展开?额,根据11x=1+x+x2+x3+....... 然后乘起来慢慢算。。不过我们有Mathematica大杀器,可以来方便的求系数,如下:

这里写图片描述

于是衬衫的价格是9磅15便士,应该选择B项。(答案应该是7)

看来没错,等等,似乎发现了什么惊天的秘密。

似乎,我们得到了p(n) 的生成函数 n=0P(n)xn=n=111xn

于是兴冲冲的来做这题,于是瞬间懵逼,完全没法啃,每次计算都不知道要花多久,跟别谈求这样一个连区间都没有的题了。

Bing了一下,这个p(n) 果然来头不小,上面的那个生成函数早就被欧拉发现了,又见欧拉!于是继续搜,找到了这个,Computing the Partitions of n,简单朴实的网页里给出了这样的一个公式。

P(n)=(1)k1(P(n12k(3k+1))+P(n12k(3k1)))

其中k从1开始,直到迭代到无法迭代,即n<0。经过观察,12k(3k+1) 是一个等差数列和的形式,其通项为2+3k ,同理后面的那一个通项为1+3k

既然是迭代公式,那么直接开好数组,一路迭代上去即可,于是代码如下:

#include <cstdio>

int* p = new int[100000]();
int PartationsP(int n)
{
    int res = 0,k = 1,a = 2,b = 1,s = 1;
    while (n >= a){
        res += s*(p[n-a] + p[n-b]);
        a += 3*k+2;
        b += 3*k+1; 
        s *= -1;
        k += 1;
    }
    res += (n >= b)? s*p[n-b]:0;
    return res % 1000000;
}

int main()
{
    p[0] = 1;
    p[1] = 1;
    int n = 1;
    do{
        n++;
        p[n] = PartationsP(n);
    }while (p[n] != 0);
    printf("%d\n",n);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章