分治演算法-大整數相乘(JAVA實現)
阿新 • • 發佈:2019-01-26
上大學演算法分析實驗課的內容.關於利用分治法大整數乘法.還沒有解決大整數的儲存方式,應該是要利用一維陣列來解決.所以目前只是5位數的運算沒有問題.程式健全
1/** *//** 2 * 大整數項乘3 * @author Administrator
4 *
5 */ 6import java.io.BufferedReader;
7import java.io.InputStreamReader;
8import java.io.IOException;
9import java.math.*;
10publicclass Test1 {
11 publicstaticvoid main(String[] args)
12 Test1 t1=new Test1();
13
14 long x,y;
15
16 System.out.println("Input x ");
17 x=t1.getNumFromConsole();
18 System.out.println("Input y ");
19 y=t1.getNumFromConsole();
20 System.out.println(t1.mult(x,y,num(x)));
21 }22 publiclong getNumFromConsole()
23 String str=null;
24 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
25 try{
26 str=br.readLine();
27 }catch(IOException ioe){
28 System.out.println(ioe.getMessage());
29 }30 return Long.parseLong(str);
31 }32 public
33 long a,b,c,d,s;
34 int e;
35 if(n==1)
36 return x*y;
37 else{
38 a=(long)(x/Math.pow(10,n/2));//取x左半部分39 b=(long)(x%Math.pow(10,n/2));//取x的又半部分40 c=(long)(y/Math.pow(10,n/2));//取y的左半部分41 d=(long)(y%Math.pow(10,n/2));
42 e=num(a);
43 s=(long)(mult(a,c,e)*Math.pow(10,n)+(mult((a-b),(d-c),e)+mult(a,c,e)+mult(b,d,e))*Math.pow(10, n/2)+mult(b,d,e));
44 return s;
45 }46 }47 //判斷輸入數字的位數48privatestaticint num(long x){
49 int i=0;
50 if(x-9<=0)
51 return1;
52 else{
53 while(x!=0){
54 i++;
55 x=x/10;
56 }57 return i;
58 }59 }60}61
其實應該用陣列來儲存大整數的,再考慮如何去完善這個程式。但分治演算法的核心思想已經盡在其中了。