原题摘录
输入正整数k,找到所有的正整数x>=y,使得1/k=1/x+1/y.
样例输入输出见文章最后.
题目分析
枚举对象为找出所有对应的x,y.那么问题在于没有终止条件无休无止的穷举下去肯定不是办法.
注意审题可知:
x,y,k均为正整数,x>=y
则1/x<=1/y
则1/k-1/y<=1/y
故y<=2k.至此我们就可以根据y计算出x
1.在编码调试过程中我们可能发现计算x的时候,x = (k*y)/(y-k);会出现小数自动进位为整数的情况下失去精度,导致数据出错.
2.在计算总共有几个符合条件的式子时,由于是先输出总个数,后输出所有符合条件的式子,所以需要用数组先将求得的符合条件的数据x,y存储起来.
AC代码
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <assert.h>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;
//形式: 1/k=1/x+1/y;
// x*y=k*(x+y);
#define maxn 1000
int main()
{
int k, x, y;
while(scanf("%d",&k) == 1){
int a[maxn], b[maxn];
int i = 0, j;
for(y = k + 1; y <= 2*k; y++)
if((k * y) % (y - k) == 0)
{ x = (k*y)/(y-k);
a[i] = x;
b[i] = y;
i++;
}
printf("%d\n",i);
for(j = 0; j < i; j++)printf("1/%d = 1/%d + 1/%d\n",k,a[j],b[j]);
}
return 0;
}

本文介绍了一种算法,用于寻找所有正整数x和y,满足1/k=1/x+1/y,其中k为给定的正整数,x>=y。通过分析得出y<=2k的条件,从而限制了搜索范围。使用C++实现,并存储符合条件的x和y以输出。
1955

被折叠的 条评论
为什么被折叠?



