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。哈哈直接套用以前的结论,验证题目中的
什么你问我怎么展开?额,根据
于是衬衫的价格是9磅15便士,应该选择B项。(答案应该是7)
看来没错,等等,似乎发现了什么惊天的秘密。
似乎,我们得到了
于是兴冲冲的来做这题,于是瞬间懵逼,完全没法啃,每次计算都不知道要花多久,跟别谈求这样一个连区间都没有的题了。
Bing了一下,这个
其中k从1开始,直到迭代到无法迭代,即n<0。经过观察,
既然是迭代公式,那么直接开好数组,一路迭代上去即可,于是代码如下:
#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;
}