比如,大数的平方(POJ 1001):
源代码:
1001 | Accepted | 164K | 0MS | C++ | 1803B | 2012-07-30 09:49:00 |
#include "stdio.h" #include "stdlib.h" #include "string.h" #define MAX 150 //乘方位数最多为6*25=150 /*将输入的"95.123"转为数组存储的95123, demical_num为小数的位数*/ void convert(char*str,int numeral[],int&demical_num) { int i,j; for(i=0,j=0;i<6;i++) { if(str[i]!='.') { numeral[j]=str[i]-'0'; j++; } else demical_num=5-i; } } /*数组a与数组result相乘,结果保存在result中*/ void muliply(int*a,int*result,int a_length,int r_length ) { int i,j; int*temp; temp=(int*)malloc((a_length+r_length)*sizeof(int)); memset(temp,0,(a_length+r_length)*sizeof(int)); for(i=0;i<a_length;i++) for(j=0;j<r_length;j++) temp[i+j+1]+=a[i]*result[j]; for(i=a_length+r_length-1;i>=0;i--) //进位处理,由低位向高位进位 { if(temp[i]>=10) { temp[i-1]+=temp[i]/10; temp[i]%=10; } } for(i=0;i<a_length+r_length;i++) result[i]=temp[i]; free(temp); } /*输出处理'0'后的结果*/ void print(int*result,int n,int demical_num) { int i,begin,end; for(i=0;i<MAX;i++) //begin为开始输出时的位置 { if(result[i]!=0&&i<=(5-demical_num)*n-1) { begin=i; break; } if(i>(5-demical_num)*n-1) { begin=(5-demical_num)*n; break; } } for(i=MAX-1;i>=0;i--) //end为结束输出时的位置 { if(result[i]!=0) { end=i; break; } if(i<(5-demical_num)*n) { end=(5-demical_num)*n-1; break; } } for(i=begin;i<=end;i++) { if(i==(5-demical_num)*n) printf(".%d",result[i]); else printf("%d",result[i]); } printf("\n"); } int main() { char str[7]; int numeral[5],result[MAX]; int i,n,demical_num; while(~scanf("%s%d",str,&n)) { memset(result,0,150*(sizeof(int))); convert(str,numeral,demical_num); for(i=0;i<5;i++) result[i]=numeral[i]; if(n==1) print(result,1,demical_num); else if(n>1) { for(i=1;i<n;i++) muliply(numeral,result,5,5*i); print(result,n,demical_num); } if(n==0) printf("1\n"); } return 0; }