java两个大整数相乘的 算法怎么写

java两个大整数相乘的 算法怎么写,第1张

有BigInteger这个类,你可以参数,如果需要自己写,应该是用字符串来处理。

import java.math.BigInteger

public class TT {

public static void main(String[] args) {

BigInteger i1 = new BigInteger("122222222222222222222222222222222")

BigInteger i2 = new BigInteger("33333333333333333333333333333333")

BigInteger result = i1.multiply(i2)

System.out.println(result.toString())

}

}

看这个:

1/** *//**

2 * 大整数项乘

3 * @author Administrator

4 *

5 */

6import java.io.BufferedReader

7import java.io.InputStreamReader

8import java.io.IOException

9import java.math.*

10public class Test1 {

11public static void main(String[] args){

12Test1 t1=new Test1()

13

14long x,y

15

16System.out.println("Input x ")

17x=t1.getNumFromConsole()

18System.out.println("Input y ")

19y=t1.getNumFromConsole()

20System.out.println(t1.mult(x,y,num(x)))

21}

22public long getNumFromConsole(){

23String str=null

24BufferedReader br=new BufferedReader(new InputStreamReader(System.in))

25try{

26str=br.readLine()

27}catch(IOException ioe){

28System.out.println(ioe.getMessage())

29}

30return Long.parseLong(str)

31}

32public long mult(long x,long y,int n){

33long a,b,c,d,s

34int e

35if(n==1)

36return x*y

37else{

38a=(long)(x/Math.pow(10,n/2))//取x左半部

39b=(long)(x%Math.pow(10,n/2))//取x的又半部分

40c=(long)(y/Math.pow(10,n/2))//取y的左半部分

41d=(long)(y%Math.pow(10,n/2))

42e=num(a)

43s=(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))

44return s

45}

46}

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

48private static int num(long x){

49int i=0

50if(x-9<=0)

51return 1

52else{

53while(x!=0){

54i++

55x=x/10

56}

57return i

58}

59}

60}

61


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8082614.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存