例题7-3 分数拆分

【题目描述】
输入正整数k,找到所有的正整数x≥y,使得1/k=1/x+1/y

input:
2
12

output:
2
21/2 = 1/6 + 1/3
1/2 = 1/4 + 1/4

8
1/12 = 1/156 + 1/13
1/12 = 1/84 + 1/14
1/12 = 1/60 + 1/15
1/12 = 1/48 + 1/16
1/12 = 1/36 + 1/18
1/12 = 1/30 + 1/20
1/12 = 1/28 + 1/21
1/12 = 1/24 + 1/24

【分析】
根据x>=y且1/k=1/x+1/y,可以推出y最大为2k,有了y与k的值,进而就可以推出x的值,如果x是整数则输出,否则跳过。可以通过一定关系推导出来的,就尽量不要去遍历它。
【代码】

#include<iostream>
#include<string>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1000 + 10;
int main()
{
	int k;
	while (scanf("%d", &k) != EOF)
	{
		for (int y = k + 1;y <= 2 * k;y++)
		{
			int x = k * y / (y - k);
			if (k * y % (y - k) == 0)
				printf("1/%d = 1/%d + 1/%d\n", k, x, y);
		}
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cprimesplus/article/details/84350082
7-3