import java.util.Scanner; class 复数 { long shi;//实部 long xu;//虚部 } public class 大整数相乘 { static long getCount(long x) {//获取一个数的位数 String str=String.valueOf(x);//转换成String类型调用length函数 return str.length(); } static long [] separate(long x) {//返回一个数的前半部分和后半部分 long count=getCount(x);//获取x的位数 if(count%2!=0) {//奇数位 count++;//使得前半部分位数少于后半部分 } long N=1; for(int i=0;i<count/2;i++) { N*=10; } long x1=x/N;//获得前半部分 long x2=x-x1*N;//获得后半部分 long y[]=new long[2]; y[0]=x1;y[1]=x2;//将其存进数组 return y;//返回数组 } static long functionB(long A,long B){//两个整数相乘 if(A<10||B<10) {//如果有一个数位数为1的时候直接相乘返回结果 return A*B; } else { long a[]=separate(A);//保存了A分成两部分的数 long b[]=separate(B);//保存了B分成两部分的数 long r1,r2,r3;//进行三次乘法运算保存的数值 r1=functionB(a[0],b[0]); r2=functionB(a[1],b[1]); r3=functionB(a[0]-a[1],b[1]-b[0]); long count=getCount(A);//获取A的位数 if(count%2!=0) {//奇数位 count++;//使得前半部分位数少于后半部分 } long N1=1;//存储10的count次方 long N2=1;//存储10的count/2次方 for(int i=1;i<=count;i++){ N1*=10; } for(int i=1;i<=count/2;i++){ N2*=10; } return r1*N1+(r1+r2+r3)*N2+r2;//只需要进行3次乘法运算即可 } } static 复数 functionC(复数 X,复数 Y){ 复数 Z=new 复数(); long r1,r2,r3; r1=functionB(X.shi,Y.shi); r2=functionB(X.xu,Y.xu); r3=functionB(X.shi-X.xu,Y.xu-Y.shi); Z.shi=r1-r2;//获得实部 Z.xu=r1+r2+r3;//获得虚部 return Z; } public static void main(String [] args) { Scanner in=new Scanner(System.in); 复数 X=new 复数(); 复数 Y=new 复数(); System.out.println("输入复数X的实部和虚部:"); X.shi=in.nextLong(); X.xu=in.nextLong(); System.out.println("输入复数Y的实部和虚部:"); Y.shi=in.nextLong(); Y.xu=in.nextLong(); //输入复数X和复数Y System.out.print(functionC(X,Y).shi);//输出实部 if(functionC(X,Y).xu>0) {//虚部大于零 System.out.print("+"+functionC(X,Y).xu+"i"); } else {//虚部小于零 System.out.print(functionC(X,Y).xu+"i"); } } }
实现复数之间的大整数乘法(分治法递归)
猜你喜欢
转载自blog.csdn.net/CWH0908/article/details/79810443
今日推荐
周排行