分数拆分(Fractions Again,Uva 10976)

原题摘录

输入正整数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;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值