A fraction whose numerator is 1 and whose denominator is a positive integer is called a unit fraction. A representation of a positive rational number p/q as the sum of finitely many unit fractions is called a partition of p/q into unit fractions. For example, 1/2 + 1/6 is a partition of 2/3 into unit fractions. The difference in the order of addition is disregarded. For example, we do not distinguish 1/6 + 1/2 from 1/2 + 1/6.
For given four positive integers p, q, a, and n, count the number of partitions of p/q into unit fractions satisfying the following two conditions.
The partition is the sum of at most n many unit fractions.
The product of the denominators of the unit fractions in the partition is less than or equal to a.
For example, if (p,q,a,n) = (2,3,120,3), you should report 4 since
enumerates all of the valid partitions.
Input
The input is a sequence of at most 200 data sets followed by a terminator.
A data set is a line containing four positive integers p, q, a, and n satisfying p,q <= 800, a <= 12000 and n <= 7. The integers are separated by a space.
The terminator is composed of just one line which contains four zeros separated by a space. It is not a part of the input data but a mark for the end of the input.
Output
The output should be composed of lines each of which contains a single integer. No other characters should appear in the output.
The output integer corresponding to a data set p, q, a, n should be the number of all partitions of p/q into at most n many unit fractions such that the product of the denominators of the unit fractions is less than or equal to a.
Sample Input
2 3 120 3 2 3 300 3 2 3 299 3 2 3 12 3 2 3 12000 7 54 795 12000 7 2 3 300 1 2 1 200 5 2 4 54 2 0 0 0 0
Sample Output
4 7 6 2 42 1 0 9 3
题意:
给一个分数,用分子为1的分数加和来构成这个分数有多少种方式。
要求每种情况分数的个数不超过n,分母乘积不超过a。
思路:根据搜索深度(最多还可以使用多少个分数);从哪个数开始搜索当前分数;
前面选出的分数的分母乘积,前面选出的分数之和的分子,前面选出的分数之和的分母来搜,满足加就1
代码:
#include <stdio.h>
#include <string.h>
#define min(a,b) ((a)<(b)?(a):(b))
#include<algorithm>
using namespace std;
int p,q,a,n,ans;
int gcd(int a,int b)//求最小公倍数
{
if(!b)
return a;
return gcd(b, a%b);
}
int exd(int np,int nq) //判断是否超过了目标值
{
return q*np>p*nq;
}
void dfs(int num,int st,int sum,int fz,int fm)
{
int i,j,nfz,nfm,lcm;
if(!num)//分母不能超过num个
return;
for(i = st; i*sum<=a; i++) //从小到大搜索当前分数的分母
{
lcm = fm*i/gcd(fm,i);//求最小公倍数,作为分数和的分母
nfm = lcm;
nfz = lcm/fm*fz+lcm/i;//分数和的分子
j = gcd(nfm,nfz);//化简分数
nfm /= j;
nfz /= j;
if(p*nfm>q*(lcm/fm*fz+lcm/i*num))//后面的分数都取最大的情况仍然达不到目标值,重要剪枝
return;
if(nfz==p && nfm==q) //达到目标值
{
ans++;
continue;
}
if(exd(nfz,nfm))//如果和已经超过了目标值,重要剪枝
continue;
dfs(num-1, i, sum*i, nfz,nfm);
}
}
int main()
{
while(scanf("%d%d%d%d",&p,&q,&a,&n) && (p+q+a+n))
{
int i;
ans=0;
i = gcd(p,q);
p /= i;
q /= i;
dfs(n,1,1,0,1);
printf("%d\n",ans);
}
return 0;
}