Project Euler 78 : Coin partitions
2017-02-14 20:19
369 查看
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(1−x)(1−x2)(1−x3)(1−x4)(1−x5)的x5的系数,唔,展开即可。
什么你问我怎么展开?额,根据11−x=1+x+x2+x3+....... 然后乘起来慢慢算。。不过我们有Mathematica大杀器,可以来方便的求系数,如下:
于是衬衫的价格是9磅15便士,应该选择B项。(答案应该是7)
看来没错,等等,似乎发现了什么惊天的秘密。
似乎,我们得到了p(n)的生成函数 ∑∞n=0P(n)xn=∏∞n=111−xn
于是兴冲冲的来做这题,于是瞬间懵逼,完全没法啃,每次计算都不知道要花多久,跟别谈求这样一个连区间都没有的题了。
Bing了一下,这个p(n)果然来头不小,上面的那个生成函数早就被欧拉发现了,又见欧拉!于是继续搜,找到了这个,Computing the Partitions of n,简单朴实的网页里给出了这样的一个公式。
P(n)=∑(−1)k−1(P(n−12k(3k+1))+P(n−12k(3k−1)))
其中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 = PartationsP(n); }while (p != 0); printf("%d\n",n); return 0; }
相关文章推荐
- Project Euler 78 : Coin partitions
- Project Euler 78:Coin partitions
- Project Euler:Problem 78 Coin partitions
- Project Euler 78
- project euler 78
- 78 bytes in Northwind.Categories.Picture
- Windows API一日一练(78)HeapAlloc函数
- 78
- project euler 第二题的数学解法
- web developer tips (78):使用文档大纲导航
- Android 2.3 r1 中文API (78)—— ViewAnimator
- [Project Euler]加入欧拉 Problem 6
- [Project Euler] 来做欧拉项目练习题吧: 题目012
- [Project Euler] Problem 12
- [Project Euler] Problem 22
- [Project Euler]Problem 5
- Project Euler 001
- Android培训班(78)Dalvik虚拟机的寄存器操作
- 怎样把工作和升职大计结合起来 http://www.people.com.cn/GB/shenghuo/78/113/20020801/790056.html
- Project Euler - Problem 3