链接地址:http://bailian.openjudge.cn/practice/2737/
题目:
- 总时间限制:
- 1000ms
- 内存限制:
- 65536kB
- 描述
- 求2个大的正整数相除的商
- 输入
- 第1行是测试数据的组数n,每组测试数据占2行,第1行是被除数,第2行是除数。每组测试数据之间有一个空行,每行数据不超过100个字符
- 输出
- n行,每组测试数据有一行输出是相应的整数商
- 样例输入
3 2405337312963373359009260457742057439230496493930355595797660791082739646 2987192585318701752584429931160870372907079248971095012509790550883793197894 10000000000000000000000000000000000000000 10000000000 5409656775097850895687056798068970934546546575676768678435435345 1- 样例输出
0 1000000000000000000000000000000 5409656775097850895687056798068970934546546575676768678435435345- 提示
- 除法比较困难,建议大家最后做这题
思路:
套用大整数模板
代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <string> 4 using namespace std; 5 6 string sub(string s1,string s2) 7 { 8 int flag = 0; 9 if(s1.length()<s2.length() || (s1.length()==s2.length() && s1 < s2)) 10 { 11 flag = 1; 12 string temp=s1; 13 s1=s2; 14 s2=temp; 15 } 16 17 18 int i,j; 19 for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--) 20 { 21 s1[i]=char(s1[i]-(j>=0?s2[j]-‘0‘:0)); //注意细节 22 if(s1[i]-‘0‘<0) 23 { 24 s1[i]=char(s1[i] + 10); 25 s1[i-1]--; 26 } 27 } 28 29 for(i = 0; i < s1.length(); i++) 30 { 31 if(s1[i] != ‘0‘) break; 32 } 33 if(i == s1.length()) i = s1.length()-1; 34 s1 = s1.substr(i); 35 36 if(flag) s1 = "-" + s1; 37 38 return s1; 39 } 40 string sum(string s1,string s2) 41 { 42 if(s1.length()<s2.length()) 43 { 44 string temp=s1; 45 s1=s2; 46 s2=temp; 47 } 48 int i,j; 49 for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--) 50 { 51 s1[i]=char(s1[i]+(j>=0?s2[j]-‘0‘:0)); //注意细节 52 if(s1[i]-‘0‘>=10) 53 { 54 s1[i]=char((s1[i]-‘0‘)%10+‘0‘); 55 if(i) s1[i-1]++; 56 else s1=‘1‘+s1; 57 } 58 } 59 return s1; 60 } 61 62 string div(string s1,string s2) 63 { 64 string res = "0"; 65 if(s1.length()<s2.length() || (s1.length()==s2.length() && s1 < s2)) 66 { 67 return "0"; 68 } 69 70 int i; 71 int sub_length = s1.length() - s2.length(); 72 for(i = sub_length; i >= 0; i--) 73 { 74 string s3(i,‘0‘); 75 string s4 = s2 + s3; 76 77 do 78 { 79 string temp = sub(s1,s4); 80 if(temp[0] == ‘-‘) break; 81 else 82 { 83 s1 = temp; 84 res = sum(res,("1" + s3)); 85 } 86 }while(1); 87 } 88 return res; 89 } 90 91 int main() 92 { 93 int n; 94 cin>>n; 95 string str1,str2; 96 while(n--) 97 { 98 cin>>str1>>str2; 99 cout<<div(str1,str2)<<endl; 100 } 101 return 0; 102 }