In mathematics, a rational number is any number that can be expressed in the form of a fraction p/q , where p & q are two integers, and the denominator q is not equal to zero. Hence, all integers are rational numbers  where denominator, in the most reduced form, is equal to 1.
You are given a list of N rational number, {a1/b1, a2/b2, ..., aN/bN}. Print the sum ( = a1/b1 + a2/b2 + ... + aN/bN = num/den) in the most reduced form.
Input
The first line of input contains an integer, N, the number of rational numbers. N lines follow. ithline contains two space separated integers, ai bi, where aiis the numerator and bi is the denominator for the ith rational number.
Output
You have to print two space separated integers, num den, where num and den are numerator and denominator of the sum respectively.
Constraints
1 <= N <= 15
1 <= ai <= 10
1 <= bi <= 10
Notes
Make sure the sum displayed as output is in the most reduced form.
If sum is an integer, you have to print 1 as denominator.
Sample Input
4
4 2
2 4
2 4
2 3
Sample Output
11 3 Explanation
Sum is 4/2 + 2/4 + 2/4 + 2/3 = (24 + 6 + 6 + 8)/12 = 44/12 = 11/3. So you have to print "11 3", which is the most reduced form.

Below is the syntax highlighted version of Rational.java from §9.2 Symbolic Methods. 摘自http://introcs.cs.princeton.edu/java/92symbolic/Rational.java.html

 /*************************************************************************
* Compilation: javac Rational.java
* Execution: java Rational
*
* Immutable ADT for Rational numbers.
*
* Invariants
* -----------
* - gcd(num, den) = 1, i.e, the rational number is in reduced form
* - den >= 1, the denominator is always a positive integer
* - 0/1 is the unique representation of 0
*
* We employ some tricks to stave of overflow, but if you
* need arbitrary precision rationals, use BigRational.java.
*
*************************************************************************/ public class Rational implements Comparable<Rational> {
private static Rational zero = new Rational(0, 1); private int num; // the numerator
private int den; // the denominator // create and initialize a new Rational object
public Rational(int numerator, int denominator) { // deal with x/0
//if (denominator == 0) {
// throw new RuntimeException("Denominator is zero");
//} // reduce fraction
int g = gcd(numerator, denominator);
num = numerator / g;
den = denominator / g; // only needed for negative numbers
if (den < 0) { den = -den; num = -num; }
} // return the numerator and denominator of (this)
public int numerator() { return num; }
public int denominator() { return den; } // return double precision representation of (this)
public double toDouble() {
return (double) num / den;
} // return string representation of (this)
public String toString() {
if (den == 1) return num + "";
else return num + "/" + den;
} // return { -1, 0, +1 } if a < b, a = b, or a > b
public int compareTo(Rational b) {
Rational a = this;
int lhs = a.num * b.den;
int rhs = a.den * b.num;
if (lhs < rhs) return -1;
if (lhs > rhs) return +1;
return 0;
} // is this Rational object equal to y?
public boolean equals(Object y) {
if (y == null) return false;
if (y.getClass() != this.getClass()) return false;
Rational b = (Rational) y;
return compareTo(b) == 0;
} // hashCode consistent with equals() and compareTo()
public int hashCode() {
return this.toString().hashCode();
} // create and return a new rational (r.num + s.num) / (r.den + s.den)
public static Rational mediant(Rational r, Rational s) {
return new Rational(r.num + s.num, r.den + s.den);
} // return gcd(|m|, |n|)
private static int gcd(int m, int n) {
if (m < 0) m = -m;
if (n < 0) n = -n;
if (0 == n) return m;
else return gcd(n, m % n);
} // return lcm(|m|, |n|)
private static int lcm(int m, int n) {
if (m < 0) m = -m;
if (n < 0) n = -n;
return m * (n / gcd(m, n)); // parentheses important to avoid overflow
} // return a * b, staving off overflow as much as possible by cross-cancellation
public Rational times(Rational b) {
Rational a = this; // reduce p1/q2 and p2/q1, then multiply, where a = p1/q1 and b = p2/q2
Rational c = new Rational(a.num, b.den);
Rational d = new Rational(b.num, a.den);
return new Rational(c.num * d.num, c.den * d.den);
} // return a + b, staving off overflow
public Rational plus(Rational b) {
Rational a = this; // special cases
if (a.compareTo(zero) == 0) return b;
if (b.compareTo(zero) == 0) return a; // Find gcd of numerators and denominators
int f = gcd(a.num, b.num);
int g = gcd(a.den, b.den); // add cross-product terms for numerator
Rational s = new Rational((a.num / f) * (b.den / g) + (b.num / f) * (a.den / g),
lcm(a.den, b.den)); // multiply back in
s.num *= f;
return s;
} // return -a
public Rational negate() {
return new Rational(-num, den);
} // return a - b
public Rational minus(Rational b) {
Rational a = this;
return a.plus(b.negate());
} public Rational reciprocal() { return new Rational(den, num); } // return a / b
public Rational divides(Rational b) {
Rational a = this;
return a.times(b.reciprocal());
} // test client
public static void main(String[] args) {
Rational x, y, z; // 1/2 + 1/3 = 5/6
x = new Rational(1, 2);
y = new Rational(1, 3);
z = x.plus(y);
System.out.println(z); // 8/9 + 1/9 = 1
x = new Rational(8, 9);
y = new Rational(1, 9);
z = x.plus(y);
System.out.println(z); // 1/200000000 + 1/300000000 = 1/120000000
x = new Rational(1, 200000000);
y = new Rational(1, 300000000);
z = x.plus(y);
System.out.println(z); // 1073741789/20 + 1073741789/30 = 1073741789/12
x = new Rational(1073741789, 20);
y = new Rational(1073741789, 30);
z = x.plus(y);
System.out.println(z); // 4/17 * 17/4 = 1
x = new Rational(4, 17);
y = new Rational(17, 4);
z = x.times(y);
System.out.println(z); // 3037141/3247033 * 3037547/3246599 = 841/961
x = new Rational(3037141, 3247033);
y = new Rational(3037547, 3246599);
z = x.times(y);
System.out.println(z); // 1/6 - -4/-8 = -1/3
x = new Rational( 1, 6);
y = new Rational(-4, -8);
z = x.minus(y);
System.out.println(z);
} }

Twitter OA prepare: Rational Sum的更多相关文章

  1. Twitter OA prepare: even sum pairs

    思路:无非就是扫描一遍记录奇数和偶数各自的个数,比如为M和N,然后就是奇数里面选两个.偶数里面选两个,答案就是M(M-1)/2 + N(N-1)/2

  2. Twitter OA prepare: Two Operations

    准备T家OA,网上看的面经 最直接的方法,从target降到1,如果是奇数就减一,偶数就除2 public static void main(String[] args) { int a = shor ...

  3. Twitter OA prepare: Equilibrium index of an array

    Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to ...

  4. Twitter OA prepare: K-complementary pair

    2sum的夹逼算法,需要sort一下.本身不难,但是tricky的地方在于允许同一个数组元素自己跟自己组成一个pair,比如上例中的[5, 5].而且数组本身就允许值相等的元素存在,在计算pair时, ...

  5. Twitter OA prepare: Anagram is A Palindrome

    Algorithm: Count the number of occurrence of each character. Only one character with odd occurrence ...

  6. Twitter OA prepare: Visit element of the array

    分析:就是建立一个boolean array来记录array里面每个元素的访问情况,遇到访问过的元素就停止visiting,返回未访问的结点个数 public int visiting(int[] A ...

  7. Twitter OA prepare: Flipping a bit

    You are given a binary array with N elements: d[0], d[1], ... d[N - 1]. You can perform AT MOST one ...

  8. PAT1081:Rational Sum

    1081. Rational Sum (20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Given N ...

  9. PAT 1081 Rational Sum

    1081 Rational Sum (20 分)   Given N rational numbers in the form numerator/denominator, you are suppo ...

随机推荐

  1. java(5) 线程

    1.理清概念 并行与并发: *并行:多个cpu实例或者多台机器同时执行一段处理逻辑,是真正的同时. *并发:通过cpu调度算法,让用户看上去同时执行,实际上从cpu操作层面不是真正的同时.并发往往在场 ...

  2. sencha touch 类的使用

    sencha touch 有一套自己的类机制,可以以面向对象的方式去写代码,封装业务逻辑,sencha touch 的组件.插件.api等都建立在这一套类机制的上面 在实际开发中,我们需要遵循这一套机 ...

  3. [原]openstack-kilo--issue(四) WARNING: nova has no endpoint in ! Available endpoints for this service:

    本博客已经添加"打赏"功能,"打赏"位置位于右边栏红色框中,感谢您赞助的咖啡. 在安装kilo的时候出现了一个报错 nova endpoints WARNING ...

  4. 关于数据库DB负载均衡的初步研究(二)

    负载均衡: 是什么:有一组服务器由路由器联系在一起,各个节点相互协作,共同负载,均衡压力. 实现原理:应用程序与DB之间有个中央控制台服务器,根据负载均衡策略决定访问哪一台DB服务器. DB服务器:读 ...

  5. 为Gem 添加环境设定

    如果在测试环境中 gem "rspec", :group => :test 当多个gem的时候 group :test do gem "webrat" g ...

  6. 使用shell数据处理数据实例①-------手把手教学版

    引子: 在工作过程中经常要处理各种小数据,同事间会用各种工具方法来处理,比如用java.python.Perl甚至用UE手工处理.但貌似不都方便. 今天举一例子使用shell来处理,来说明shell一 ...

  7. AngularJS初始(一)

    什么是AngularJs? angularjs是一个为动态WEB应用设计的结构框架.它能让你使用HTML作为模板语言,通过扩展HTML的语法,让你能更清楚.简洁地构建你的应用组件.它的创新点在于,利用 ...

  8. vue--简单数据绑定

    <template> <div id="app"> {{msg}} //绑定数据 {{obj.name}} //绑定对象 <p v-for=" ...

  9. 关于JavaScript转义字符('、 " 、\" 、\')【原创】

    先插入一条广告,博主新开了一家淘宝店,经营自己纯手工做的发饰,新店开业,只为信誉!需要的亲们可以光顾一下!谢谢大家的支持!店名: 小鱼尼莫手工饰品店经营: 发饰.头花.发夹.耳环等(手工制作)网店: ...

  10. dataframe转换为多维矩阵,然后可以使用values来实现

    import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(3,3),columns=list('abc'),ind ...