大数乘法

author author     2023-03-25     761

关键词:

An example of Karatsuba algorithm for multiplication of n digit numbers.
  1. import java.math.BigInteger;
  2. import java.util.Random;
  3. import java.io.*;
  4.  
  5. public class Karatsuba {
  6.  
  7. /**
  8.   * M���©todo que mediante la t���©cnica divide y vencer���¡s, multiplica dos n���ºmeros
  9.   * muy grandes tras una serie de pasos.
  10.   * @param u BigInteger Entero grande 1.
  11.   * @param v BigInteger Entero grande 2.
  12.   * @return BigInteger Resultado
  13.   * JOSE PINO
  14.   */
  15. public static BigInteger karatsuba(BigInteger u, BigInteger v) {
  16. int posiciones = Math.max(u.bitLength(), v.bitLength());
  17.  
  18. //Para n menor que mil, es m���¡s eficiente la multiplicaci���³n normal.
  19. if (posiciones <= 1000) {
  20. return u.multiply(v);
  21. }
  22. posiciones = posiciones / 2;
  23.  
  24. /*
  25.   * Repartimos en trocitos:
  26.   * u = w * 2^n + x
  27.   * v = y * 2^n + z
  28.   */
  29.  
  30. BigInteger w = u.shiftRight(posiciones);
  31. BigInteger x = u.subtract(w.shiftLeft(posiciones));
  32. BigInteger y = v.shiftRight(posiciones);
  33. BigInteger z = v.subtract(y.shiftLeft(posiciones));
  34.  
  35. // Calculamos los resultados parciales
  36. BigInteger p = karatsuba(w, y); //p=w*y
  37. BigInteger q = karatsuba(x, z); //q=x*z
  38. BigInteger r = karatsuba(x.add(w), z.add(y)); //r=(x+w)*(z+y)
  39. BigInteger z1 = r.subtract(p).subtract(q); //r-p-q
  40.  
  41. // Se juntan los resultados parciales para obtener el resultado global.
  42. return p.shiftLeft(2 * posiciones).add(z1.shiftLeft(posiciones)).add(q);
  43. }
  44.  
  45. public static void main(String[] args) {
  46. Random rnd = new Random();
  47.  
  48. System.out.println("ALGORITMO DE KARATSUBA");
  49. System.out.println("----------------------");
  50.  
  51. System.out.print(
  52. "Introduzca un n���ºmero de bits(Sugerencia: A poder ser mayor que 1000): ");
  53.  
  54.  
  55. try {
  56. String numero = br.readLine();
  57.  
  58. int N = Integer.parseInt(numero);
  59.  
  60. //Creamos dos n���ºmeros al azar de N cifras.
  61. BigInteger x = new BigInteger(N, rnd);
  62. BigInteger y = new BigInteger(N, rnd);
  63.  
  64. //System.out.println("Numero 1: " + x);
  65. //System.out.println(" Numero 2: " + y);
  66. System.out.println("Multiplicamos...");
  67.  
  68. //Mediremos los tiempos de Karatsuba y Multiplicaci���³n normal para ver las diferencias.
  69. long t = System.nanoTime();
  70.  
  71. //z ser���­a el resultado. Hacemos la llamada al m���©todo.
  72. BigInteger z = karatsuba(x, y);
  73.  
  74. t = System.nanoTime() - t;
  75. System.out.printf(" El valor de X es: %d " , x);
  76. System.out.printf(" El valor de Y es: %d " , y);
  77. System.out.printf(" El resultado de X*Y mediante Karatsuba es: %d " , z);
  78. System.out.println(" N = " + N);
  79. System.out.println(" N = " + N);
  80. System.out.println("Karatsuba: tiempo = " + t);
  81.  
  82. t = System.nanoTime();
  83. z = x.multiply(y);
  84. t = System.nanoTime() - t;
  85. System.out.println("Multiplicaci���³n Normal: tiempo = " + t);
  86.  
  87. }
  88. System.err.println("Atenci���³n: Car���¡cter no valido.");
  89. System.exit( -1);
  90. }
  91. catch (IOException ioe) {
  92. System.err.println("Error de E/S");
  93. System.exit( -1);
  94. }
  95. catch (Exception e) {
  96. System.err.println("Error inesperado. " + e.getMessage());
  97. System.exit( -1);
  98. }
  99. }
  100. }

(转)大数运算——大数乘法

转自:http://blog.csdn.net/lisp1995/article/details/52316466首先说一下乘法计算的算法:同样是模拟人工计算时的方法。从低位向高位乘,在竖式计算中,我们是将乘数第一位与被乘数的每一位相乘,记录结果之后,用第二位相乘,记录结... 查看详情

karatsuba乘法--实现大数相乘(代码片段)

...chKaratsuba提出,并于1962年得以发表。此算法主要用于两个大数相乘。普通乘法的复杂度是n2,而Karatsuba算法的复杂度仅为3nlog3≈3n1.585(log3是以2为底的)。算法介绍步骤简介Karatsuba算法主要应用于两个大数的相乘,原理是将大数... 查看详情

大数加法大数乘法(代码片段)

大数加法hdu1002 #include<iostream>#include<cstdio>#include<string>#include<cstring>#include<cmath>#include<sstream>#include<algorithm>#include<set>#inc 查看详情

大数运算——大数乘法(代码片段)

 #include<iostream>#include<string>#include<algorithm>usingnamespacestd;constintMAX=1005;intmain()intx[MAX]=0,y[MAX]=0,z[2*MAX+1]=0;stringa,b;cin>>a>>b;revers 查看详情

大数乘法

publicstaticStringmul(Stringstr1,Stringstr2){intminLength=-1;intmaxLength=-1;if(str1.length()>str2.length()){minLength=str2.length();maxLength=str1.length();}else{minLength=str1.length();maxLength= 查看详情

大数乘法

#include<iostream>#include<cstring>usingnamespacestd;#defineMAX1000000structNode{intdata;Node*next;};voidoutput(Node*head){if(!head->next&&!head->data)return;output(head-> 查看详情

大数乘法

给出2个大整数A,B,计算A*B的结果。 Input第1行:大数A第2行:大数B(A,B的长度 <= 1000,A,B >= 0)Output输出A * BInput示例123456234567Output示例28958703552解法:第i位数乘第j位数,乘积是第i+j位数(从0开始) 如... 查看详情

51nod1027大数乘法

1027 大数乘法基准时间限制:1 秒空间限制:131072 KB分值: 0 难度:基础题 给出2个大整数A,B,计算A*B的结果。 Input第1行:大数A第2行:大数B(A,B的长度 <= 1000,A,B >= 0)Output输出A *&n... 查看详情

大数乘法——模板

voidmulti(inta[],intb[],intc[],intan,intbn,int&cn)//a[]被乘数b[]乘数c[]保存结果 //an表示a数组中所存大数的位数,bn表示b数组中所存大数的位数,cn存c数组的位数 for(inti=maxn-1;i>=maxn-bn;i--) //乘数 intweight=0; //进位数 for(i 查看详情

1027大数乘法

给出2个大整数A,B,计算A*B的结果。Input第1行:大数A第2行:大数B(A,B的长度 <= 1000,A,B >= 0)Output输出A*BInput示例123456234567Output示例289587035521#include<stdio.h>2#include<stdlib.h>3#include< 查看详情

大数乘法

#include<cstdio>#include<cstring>#include<string>voidreverseOrder(char*str,intp,intq)  chartemp;  while(p<q)      temp=str[p];& 查看详情

大数乘法

...的情形。为避免溢出,可以采用字符串的方法来实现两个大数之间的乘法。具体来说,首先以字符串的形式输入两个整数,每个整数的长度不会超过8位,然后把它们相乘的结果存储在另一个字符串当中(长度不会超过16位),最... 查看详情

大数乘法

方法:和加减法类似,同样是用字符串数组存储,再转化为整形数组步骤:1、反向存储(反转),转化为整形   2、乘积进位    3、逆序输出#include<bits/stdc++.h>usingnamespacestd;chara[1005];charb[1005];intaa[1005];intbb[1005];i... 查看详情

四:大数运算-乘法运算

问题:大数-乘法运算题目描述请计算两个整数相乘(数的范围为:0<=num<10^100)输入两个整数输出一个整数样例输入1000000010000000样例输出1000000000000001#include<stdio.h>2#include<string.h>3#defineM10000004intInter_Sum[M];5intInter_jie[M]; 查看详情

大数乘法

#include#include#includeusingnamespacestd;intstr1[100],str2[100],res[100];intlen1,len2,len3;voidsetData(){ strings1,s2; cin>>s1>>s2; reverse(s1.begin(),s1.end());reverse(s2.begin(),s2.end( 查看详情

1028大数乘法v2(fftorpy)

1028 大数乘法 V2基准时间限制:2 秒空间限制:131072 KB分值: 80 难度:5级算法题给出2个大整数A,B,计算A*B的结果。 Input第1行:大数A第2行:大数B(A,B的长度 <= 100000,A,B >= 0)Output输出A... 查看详情

51nod1027大数乘法

题目链接:51nod1027大数乘法直接模板了。1#include<cstdio>2#include<cstring>3usingnamespacestd;4constintN=1001;5constintDLEN=4;6constintmod=10000;7intalen,blen;8intans_len;9chara1[N],b1[N];10inta[600],b[60 查看详情

大数乘法?

#defineMAX_INPUT_SIZE10000#defineMAX_RESULT_SIZE(MAX_INPUT_SIZE*2-1)chara[MAX_INPUT_SIZE],b[MAX_INPUT_SIZE],res[MAX_RESULT_SIZE];voidmult(charresult[],chara[],charb[])//res一定要清空{intal,bl;//alength,ble 查看详情