您的位置:首页 > 编程语言 > Java开发

分治算法-大整数相乘(JAVA实现)

2011-11-29 23:30 267 查看
 上大学算法分析实验课的内容.关于利用分治法大整数乘法.还没有解决大整数的存储方式,应该是要利用一维数组来解决.所以目前只是5位数的运算没有问题.程序健全

 1



/** *//**
 2

 * 大整数项乘
 3

 * @author Administrator
 4

 *
 5

 */
 6

import java.io.BufferedReader;
 7

import java.io.InputStreamReader;
 8

import java.io.IOException;
 9

import java.math.*;
10



public class Test1 

{
11



    public static void 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



    public long 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 long mult(long x,long y,int n)

{
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

    //判断输入数字的位数
48



    private static int num(long x)

{
49

        int i=0;
50

        if(x-9<=0)
51

            return 1;
52



        else

{
53



            while(x!=0)

{
54

                i++;
55

                x=x/10;
56

            }
57

            return i;
58

        }
59

    }    
60

}
61


其实应该用数组来保存大整数的,再考虑如何去完善这个程序。但分治算法的核心思想已经尽在其中了。  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 java string null 存储 c