1081. Rational Sum (20) -最大公約數

題目如下:

Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum.

Input Specification:

Each input file contains one test case. Each case starts with a positive integer N (<=100), followed in the next line N rational numbers "a1/b1 a2/b2 ..." where all the numerators and denominators are in the range of "long int". If there is a negative number, then the sign must appear in front of the numerator.

Output Specification:

For each test case, output the sum in the simplest form "integer numerator/denominator" where "integer" is the integer part of the sum, "numerator" < "denominator", and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.

Sample Input 1:
5
2/5 4/15 1/30 -2/60 8/3
Sample Output 1:
3 1/3
Sample Input 2:
2
4/3 2/3
Sample Output 2:
2
Sample Input 3:
3
1/3 -1/6 1/8
Sample Output 3:
7/24



題目要求對分數進行處理,題目的關鍵在于求取最大公約數,最初我采用了循環出現超時,后來改用輾轉相除法,解決了此問題。需要注意的是分子為負數的情況,為方便處理,我們把負數取絕對值,并且記錄下符號,最后再輸出。

輾轉相除法如下:

給定數a、b,要求他們的最大公約數,用任意一個除以另一個,得到余數c,如果c=0,則說明除盡,除數就是最大公約數;如果c≠0,則用除數再去除以余數,如此循環下去,直至c=0,則除數就是最大公約數,直接說比較抽象,下面用例子說明。

設a=25,b=10,c為余數

①25/10,c=5≠0,令a=10,b=5。

②10/5,c=0,則b=5就是最大公約數。

求取最大公約數的代碼如下:

long getMaxCommon(long a, long b){long yu;if(a == b) return a;while(1){yu = a % b;if(yu == 0) return b;a = b;b = yu;}
}

完整代碼如下:

#include <iostream>
#include <stdio.h>
#include <vector>using namespace std;struct Ration{long num;long den;Ration(long _n, long _d){num = _n;den = _d;}};long getMaxCommon(long a, long b){long yu;if(a == b) return a;while(1){yu = a % b;if(yu == 0) return b;a = b;b = yu;}
}int main(){int N;long num,den;long maxDen = -1;cin >> N;vector<Ration> rations;for(int i = 0; i < N; i++){scanf("%ld/%ld",&num,&den);rations.push_back(Ration(num,den));if(maxDen == -1){maxDen = den;}else{// 找maxDen和當前的最小公倍數if(den == maxDen) continue;else if(maxDen > den){if(maxDen % den == 0) continue;}else{if(den % maxDen == 0){maxDen = den;continue;}}maxDen = maxDen * den;}}num = 0;for(int i = 0; i < N; i++){num += rations[i].num * (maxDen / rations[i].den);}if(num == 0) {printf("0\n");return 0;}bool negative = num < 0;if(negative) num = -num;if(num >= maxDen){long integer = num / maxDen;long numerator = num % maxDen;if(numerator == 0){if(negative)printf("-%ld\n",integer);elseprintf("%ld\n",integer);return 0;}long common = getMaxCommon(numerator,maxDen);if(negative){printf("%ld -%ld/%ld\n",integer,numerator/common,maxDen / common);}else{printf("%ld %ld/%ld\n",integer,numerator/common,maxDen / common);}}else{long common = getMaxCommon(num,maxDen);if(negative)printf("-%ld/%ld\n",num/common,maxDen/common);elseprintf("%ld/%ld\n",num/common,maxDen/common);}return 0;
}


轉載于:https://www.cnblogs.com/aiwz/p/6154051.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/459031.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/459031.shtml
英文地址,請注明出處:http://en.pswp.cn/news/459031.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

CRC8校驗分析

*************************************************** 更多精彩&#xff0c;歡迎進入&#xff1a;http://shop115376623.taobao.com *************************************************** CRC即循環冗余校驗碼&#xff08;Cyclic Redundancy Check&#xff09;&#xff1a;是…

insert mysql后加where,如何在MySQL Insert語句中添加where子句?

This doesnt work:這不起作用:INSERT INTO users (username, password) VALUES ("Jack","123") WHERE id1;Any ideas how to narrow insertion to a particular row by id?任何想法如何通過id縮小插入到特定行?8 個解決方案#120In an insert statement y…

阿里云使用筆記-Lrzsz上傳下載文件-centos7

2019獨角獸企業重金招聘Python工程師標準>>> 上傳文件時提示&#xff1a; -bash: rz: command not found rz命令沒找到&#xff1f; 執行sz&#xff0c;同樣也沒找到。 原來是要安裝個叫 lrzsz 的東西&#xff0c;一查可以直接yum。 安裝lrzsz&#xff1a;# yum -y …

C#中的DBNull、Null、String.Empty和“”

null可賦值任何變量,將變量置為空 DBNull只用于DataRow對象,表示數據庫中的空值 String.Empty是0長度字串 Convert.IsDBNull判斷是否為DBNull DBNull.Value與Null的區別 Null是.net中無效的對象引用。 DBNull是一個類。DBNull.Value是它唯一的實例。它指數據庫中數據為空(&l…

matlab數值很小出錯,求大神幫忙解決一下,用MATLAB求解動力學數據總是出錯~ - 計算模擬 - 小木蟲 - 學術 科研 互動社區...

CODE:function KineticsEst5 % 動力學ODE方程模型的參數估計%%%% The variables y here are y(1)xB, y(2)xoNB, y(3)xmNB,y(4)xpNB,y(5)xDNB .clear allclck0 [5 5 5 5 5]; % 參數初值lb [0 0 0 0 0]; % 參數下限ub [inf inf inf inf inf]; % 參數上限x0 [0 0 0 0 0 0];Kin…

iOS開發--驗證碼

第一步&#xff0c;拖兩個空間textfiled和button到storyboard上的viewcontroller上。 第二步&#xff0c;拖線&#xff0c;鏈接到.h文件中代碼如下&#xff1a; 1property (weak, nonatomic) IBOutlet UIButton *l_timeButton;第三步&#xff0c;在,m文件中為l_timeButton設置監…

Standard C Episode 8

C語言函數和程序結構 通過函數可以把大的計算任務分解成若干個較小任務&#xff0c;從而使得思路更加清晰&#xff0c;同時函數也大大提高了代碼的復用率&#xff0c;提高了工作效率。要注意的是多函數之間應該盡可能地高聚合低耦合。另一方面&#xff0c;一個程序可以保存在一…

C# Socket 編程詳解

Microsoft.Net Framework為應用程序訪問Internet提供了分層的、可擴展的以及受管轄的網絡服務&#xff0c;其名字空間System.Net和 System.Net.Sockets包含豐富的類可以開發多種網絡應用程序。.Net類采用的分層結構允許應用程序在不同的控制級別上訪問網絡&#xff0c;開發人員…

java 線程池 wait,Java 多線程 之 wait等待 線程實例

package com.wait.notify;/**題目: 人們在火車站的售票窗口排隊買火車票1. 北京西站開門2. 打開售票窗口3. 北京西站有10張去長沙的票4. 打開2個售票窗口,5 假設每個售票窗口每隔1秒鐘買完一張票1. 根據 名詞 找類人們(Person), 火車站(Station),火車票(Ticket) , 售票窗口e 是…

002 exercises

求列表全排列lst [1,2,3] l1 [(x,y,z) for x in lst for y in lst for z in lst if x ! y if y ! z if x ! z] print(l1)給定一個非負整數num,重復的加每一位,直到最后只剩下一位例如: num 38,計算過程如下:3 8 111 1 2最后輸出結果為2#遞歸 def add(num):if len(str(num…

(線段樹 點更新 區間求和)lightoj1112

鏈接&#xff1a; http://acm.hust.edu.cn/vjudge/contest/view.action?cid88230#problem/D &#xff08;密碼0817&#xff09; Description Robin Hood likes to loot rich people since he helps the poor people with this money. Instead of keeping all the money togeth…

TCP/ip通信模式

TCP/IP 應用層與應用程序*************************************************** 更多精彩&#xff0c;歡迎進入&#xff1a;http://shop115376623.taobao.com *************************************************** 文檔出處&#xff1a;http://blog.csdn.net/bingxx11/article…

PHP中判斷空的方法,php中類型判斷和NULL,空值檢查的方法

在一些接口和數據庫的設計中。數據庫的非必填字段可能為null或者為空。這個時候接口前端javascript去判斷的時候就會比較麻煩。為了便于統一的判斷。一律把null和 空裝換成 空.這樣前端的判斷就變得簡潔 if(aa ){........}建議使用 或者 來判斷。。以下是我簡短的一個把數據…

8 Regular Expressions You Should Know

2019獨角獸企業重金招聘Python工程師標準>>> Regular expressions are a language of their own. When you learn a new programming language, theyre this little sub-language that makes no sense at first glance. Many times you have to read another tutori…

poj 3278 catch that cow BFS(基礎水)

Catch That CowTime Limit: 2000MS Memory Limit: 65536KTotal Submissions: 61826 Accepted: 19329Description Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a num…

制作已編譯的html幫助文件

http://www.cnblogs.com/cm186man/archive/2008/03/10/1098896.html引用 HTML幫助文檔從結構上來看可分為兩個部分&#xff0c;運行器和文檔內容。它的一個好處是能使幫助文檔跨平臺運行&#xff0c;只要有不同平臺上的運行器和瀏覽器&#xff0c;幫助文檔不再需要重新編制&…

matlab %3c handle,volume browser (updated).htm 源代碼在線查看 - Matlab顯式三維地震數據的源代碼 資源下載 蟲蟲電子下載站...

Comments: any comments on this error:??? Error using > timesIntegers can only be combined with integers of the same class, or scalar doubles.Error in > interp3>linear at 368 F (( arg4(ndx).*(1-t) arg4(ndx1).*t ).*(1-s) ...Error in > inter…

PHPer轉戰Android的學習過程以及Android學習

原文作者&#xff1a; eoeadmin原文地址&#xff1a; http://my.eoe.cn/shuhai/archive/19684.html--------------------------------------------這篇文章主要寫了一個PHP程序猿是如何轉戰學習Android的。 第一步&#xff1a;直接跨過java的學習&#xff0c;原因有我之前看過畢…

SQL中實現截取字符串的函數

SQL中實現截取字符串的函數 如果想實現從數據庫中取數據時截取一個字段下的內容或者截取一串字符串&#xff0c;則能夠實現這種效果的函數有Left&#xff0c;Right&#xff0c;SubString三個函數。1.Left函數&#xff1a;Left&#xff08;character_expression , integer_expre…

php時區設置問題,PHP 的時區設置問題_PHP教程

裝上PHP5后你會發現這樣的問題&#xff1a;你也許會發現&#xff0c;輸出的時間和你現在的時間是不相同的。原因是假如你不在程序或配置文件中設置你的服務器當地時區的話&#xff0c;PHP所取的時間是格林威治標準時間&#xff0c;所以和你當地的時間會有出入。格林威治標準時間…