第十届蓝桥杯 JavaA 分数

第十届蓝桥杯 JavaA 分数


标题:分数

1/1 + 1/2 + 1/4 + 1/8 + 1/16 + …
每项是前一项的一半,如果一共有20项,
求这个和是多少,结果用分数表示出来。
类似:
3/2
当然,这只是加了前2项而已。分子分母要求互质。

注意:
需要提交的是已经约分过的分数,中间任何位置不能含有空格。
请不要填写任何多余的文字或符号。


答案: 1048575/524288
法一:
思路:
通分,分别求分子分母,约分。
import java.math.BigInteger;

/**
 * 
 * 1.通分,分别求出分子,分母 
 * 2.求gcd ,利用gcd约分
 * @param args
 */
public class 结果填空1分数 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BigInteger a = BigInteger.ONE;// 分子
		BigInteger b = new BigInteger((int) Math.pow(2, 19) + "");// 分母
		BigInteger sum = BigInteger.ZERO;// 分子和
		// 求分子
		for (int i = 1; i <= 20; ++i) {
			sum = sum.add(a);
			a = a.multiply(new BigInteger("2"));
		}

		// 分子分母最大公约数
		BigInteger gcd = sum.gcd(b);
		System.out.println(sum.divide(gcd) + "/" + b.divide(gcd));
	}
}


法二(最优):
思路:
利用等比数列求和公式化简,求分子分母,约分。
package JavaA.s9;

import java.math.BigInteger;
/**
 * https://blog.csdn.net/linruier2017/article/details/79782950 
 * 1.利用等比数列求和公式化简
 * 2.求分子分母 
 * 3.利用gcd约分
 * 
 * @param args1048575/524288
 */
public class 结果填空1分数1 {

	public static void main(String[] args) {
		int a = (int) (Math.pow(2, 20) - 1);// 分子
		int b = (int) (Math.pow(2, 19));// 分母

		// 分子分母最大公约数
		int gcd = gcd(a, b);
		System.out.println(a / gcd + "/" + b / gcd);
	}

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

	static int lcm(int a, int b) {
		return (a * b) / gcd(a, b);
	}
}




法三:
思路:
表示成分数形式,化简,计算。
class Fraction {
	long up;
	long down;

	public Fraction() {
	}

	public Fraction(long up, long down) {
		this.up = up;
		this.down = down;
	}
}

/**
 * 表示成分数形式,化简,计算
 * 
 * @description TODO
 * @author frontier
 * @time 2019年3月22日 下午8:55:53
 *
 */
public class 结果填空1分数2 {
	public static void main(String[] args) {
		Fraction res = new Fraction(0, 1);
		for (long i = 0; i < 20; ++i) {
			res = add(res, new Fraction(1, (int) Math.pow(2, i)));
			res = reduce(res);
		}
		System.out.println(res.up + "/" + res.down);

	}

	static Fraction add(Fraction a, Fraction b) {
		Fraction c = new Fraction();
		c.up = a.up * b.down + b.up * a.down;
		c.down = a.down * b.down;
		return reduce(c);
	}

	static Fraction multi(Fraction a, Fraction b) {
		Fraction c = new Fraction();
		c.up = a.up * b.up;
		c.down = a.down * b.down;
		return reduce(c);
	}

	static Fraction reduce(Fraction n) {
		if (n.down < 0) {
			n.down *= -1;
			n.up *= -1;
		}
		if (n.up == 0) {
			n.down = 1;
		} else {
			long g = gcd(n.up, n.down);
			n.up /= g;
			n.down /= g;
		}
		return n;
	}

	static long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值