MENU

第九届蓝桥杯 Java A—— 分数

March 22, 2019 • Read: 3705 • 算法阅读设置

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

注意:
需要提交的是已经约分过的分数,中间任何位置不能含有空格

  • public class Main {
  • public static void main(String[] args) {
  • Rational res = new Rational(1, 1);
  • for (int i = 1; i < 20; i++)
  • res = res.add(new Rational(1, (long) Math.pow(2, i)));
  • System.out.println(res);
  • }
  • }
  • class Rational {
  • long a, b; // Numerator, denominator
  • long gcd(long a, long b) {
  • return b == 0 ? a : gcd(b, a % b);
  • }
  • Rational(long a, long b) {
  • this.a = a;
  • this.b = b;
  • long k = gcd(a, b);
  • if (k > 1) {
  • this.a /= k;
  • this.b /= k;
  • }
  • }
  • @Override
  • public String toString() {
  • return String.format("%d/%d", a, b);
  • }
  • Rational add(Rational x) {
  • return new Rational(a * x.b + x.a * b, b * x.b);
  • }
  • }
Archives Tip
QR Code for this page
Tipping QR Code