蓝桥杯国赛之埃及分数

题目:埃及分数

古埃及曾经创造出灿烂的人类文明,他们的分数表示却很令人不解。古埃及喜欢把一个分数分解为类似: 1/a + 1/b 的格式。

这里,a 和 b 必须是不同的两个整数,分子必须为 1

比如,2/15 一共有 4 种不同的分解法(姑且称为埃及分解法):

1/8 + 1/120
1/9 + 1/45
1/10 + 1/30
1/12 + 1/20

那么, 2/45 一共有多少个不同的埃及分解呢(满足加法交换律的算同种分解)? 请直接提交该整数(千万不要提交详细的分解式!)。

请严格按照要求,通过浏览器提交答案。
注意:只提交分解的种类数,不要写其它附加内容,比如:说明性的文字

答案:


import java.util.Scanner;

public class Main
{

    public static int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        int d = a % b;
        return gcd(b, d);
    }

    public static void main(String[] args)
    {
        int count = 0;
//      暴力搜索,两层for循环,分别定 a 和 b ;根据两个分数求和的运算规则,
//      通分--sum1 = a * b
//      分子相加--sum2 = a + b
//      得到分数后,求出分子与分母的最大公约数;利用递归型辗转相除法 ,求出分子与分母的最大公约数,
//      约分后a1 = sum1 / t, a2 = sum2 / t; if判断分子a2是否==2;分母a1是否==45 。
//      如果等于则输出结果。
//      把遍历的范围扩大,算出多少就是多少了。
        for (int i = 2; i <= 19900; i++)
        {
            for (int j = i + 1; j <= 19900; j++)
            {
                int a = i, b = j;
                int sum1 = a * b, sum2 = a + b;
                int t = gcd(sum2, sum1);
                int a1 = sum1 / t, a2 = sum2 / t;
                if (a1 == 45 && a2 == 2)
                {
                    System.out.println("1/" + a + " + 1/" + b + " = 2/45");
                    count++;
                }
            }
        }
        System.out.println(count);
        // printf("%d\n", );
        // return 0;
    }
}

心得:

求两个数的最大公约数:
public static void main(String[] args)
    {
        System.out.println(gcd(700,140));
        System.out.println("OK");
    }
    public static int gcd(int a, int b)
    {
        if (b == 0)
            return a;
        int d = a % b;
        return gcd(b, d);
    }

140
OK

猜你喜欢

转载自blog.csdn.net/qq_37905259/article/details/80570071