版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bear_huangzhen/article/details/78513838
【题目】
古埃及曾经创造出灿烂的人类文明,他们的分数表示却很令人不解。
古埃及喜欢把一个分数分解为类似: 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 一共有多少个不同的埃及分解呢(满足加法交换律的算同种分解)?
请直接提交该整数(千万不要提交详细的分解式!)。
请严格按照要求,通过浏览器提交答案。
注意:只提交分解的种类数,不要写其它附加内容,比如:说明性的文字
【分析】
2/45 = 1/a + 1/b , 假设a<b,很明显22<a<45。因为1/22>2/45,1/45 <= 2/45。
我们用2/45-1/a就可以求出1/b,进而求出b。
【源码】
public static void main(String[] args) {
//新建2/45
Rational r = new Rational(2, 45);
//计数变量
int counter = 0;
for (int a = 23; a < 45; a++) {
Rational ra = new Rational(1, a);
Rational rb = r.sub(ra);
if(rb.x == 1 && rb.y > a) {
System.out.println(ra.toString() + "+" + rb.toString());
counter++;
}
}
System.out.println(counter);
}
public class Rational {
int x;
int y;
public Rational(int x, int y){
int gcd = gcd(x,y);
this.x = x/gcd;
this.y = y/gcd;
}
//辗转相除法求最大公约数
//(10,5) == (5,0) == 5
private int gcd(int x, int y){
if(y == 0) return x;
return gcd(y,x%y);
}
//x1/y1 +x2/y2 == (x1y2+x2y1)/y1y2
public Rational add(Rational r){
return new Rational(this.x*r.y + r.x*this.y, this.y*r.y);
}
//x1/y1 - x2/y2 = (x1y2-x2y1)/y1y2
public Rational sub(Rational r) {
return new Rational(this.x*r.y - r.x*this.y, this.y*r.y);
}
@Override
public String toString() {
return this.x +"/" + this.y;
}
}
【结果 】
1/23+1/1035
1/24+1/360
1/25+1/225
1/27+1/135
1/30+1/90
1/35+1/63
1/36+1/60
7种