zoukankan      html  css  js  c++  java
  • 分数拆分

     It is easy to see that for every fraction in the form(k > 0), we can always find two positive integers x and y,x ≥ y, such that:

    Now our question is: can you write a program that counts how many such pairs of x and y there are for any given k?

    Input

    Input contains no more than 100 lines, each giving a value of k (0 < k ≤ 10000).

    Output

    For each k, output the number of corresponding (xy) pairs, followed by a sorted list of the values of x and y, as shown in the sample output.

    Sample Input

    2
    12
    

    Sample Output

    2
    1/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

     法一:

    #include<cstdio>
    #include<iostream>
    #include<cstdio>
    using namespace std;
    int main()
    {
       int k,n;
       while( ~scanf("%d",&k))
       { 
       int cnt=0;
        if(k==0) return 0;
       
       for(int i=k+1;i<=2*k;i++)
       {
           if(((i*k)%(i-k))==0) cnt++; 
       }
        printf("%d
    ",cnt);
       for(int i=k+1;i<=2*k;i++)
       {
            printf("1/%d = 1/%d + 1/%d
    ",k,(i*k)/(i-k),i);
       }
    }
        return 0;
    }

    法二:

    #include<cstdio>
    #include<iostream>
    #include<vector>
    #include<algorithm>
    using namespace std;
    vector<pair<int,int> > vec;
    int main()
    {
        int n,x,y;
        while(~scanf("%d",&n))
        {
            vec.clear();
            int cnt=0;
            for(int i=n+1;i<=2*n;i++)
            {
                if((i*n)%(i-n)==0)
                {
                    x=i;
                    y=i*n/(i-n);
                    if(x<y) swap(x,y);
                    vec.push_back(make_pair(x,y));
                    cnt++;
                }
            }
        
        sort(vec.begin(),vec.end());
        printf("%d
    ",cnt);
        for(int i=cnt-1;i>=0;i--)
        printf("1/%d = 1/%d + 1/%d
    ",n,vec[i].first,vec[i].second);
    }
         return 0;
    }

    AC题总结:

    1.最后输出格式要与题意一致

    2.时间超时的时候注意方法

    3.输入scanf的返回值判断

  • 相关阅读:
    深入了解抽象类和接口
    关于Hibernate查询对象调用set方法自动同步到数据库解决方案
    【鸽子的迷信(一)】python导入由excel文件改后缀变成的csv文件出现乱码错误(ParserError:Error tokenizing data. C error:)
    《计算机操作系统》CH1操作系统引论思维导图整理
    IntelliJ IDEA创建一个Maven项目
    C++实验三
    小练习
    C++实验二
    C++的ch1&ch2的整理
    C++实验一
  • 原文地址:https://www.cnblogs.com/is-Tina/p/7487611.html
Copyright © 2011-2022 走看看