Advertisement
LinKin

KaratSuva

Nov 5th, 2012
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.25 KB | None | 0 0
  1. /*
  2.  * Biginteger multiplication
  3.  * Algorithm: Karatsuva multiplication
  4.  * Order: n^1.58
  5.  * Note : 1) All the number should be kept in reverse order in vector
  6.           2) After all computation Ans should be normalized
  7.           3) BASE should be kept such that BASE*logn*32 doesnt overflow
  8.           4) initially for two numbers lentg should be power of ontherwise
  9.              otherwise padded extra field with zero
  10.  */
  11.  
  12. #include<stdio.h>
  13. #include<string.h>
  14. #include<vector>
  15. #include<algorithm>
  16. using namespace std;
  17. /* can be set any value like 10^8 */
  18. const long BASE = 10;
  19. /* used to set all value base 10 or defined Base*/
  20. void Norm( vector<long> &A ){
  21.     long i,Carry = 0;
  22.     for( i=0;i<A.size();i++ ){
  23.         long v = A[i] + Carry;
  24.         A[i] = v%BASE;
  25.         Carry = v/BASE;
  26.     }
  27. }
  28. /* to check is all value of A is zero  */
  29. bool AllZero( vector<long> &A ){
  30.     long i;
  31.     for( i=0;i<A.size();i++ ){
  32.         if( A[i] ) return false;
  33.     }
  34.     return true;
  35. }
  36. /* multiple to num A and B , result in Ret */
  37. /* A should be represented as A1*Base^(n/2) + A0 */
  38. /* B should be represented as B1*Base^(n/2) + B0 */
  39. void KaratSuva( vector<long> &A,vector<long> &B,vector<long> &Ret ){
  40.     long i,j,n = A.size();
  41.     Ret.resize( 2*n );
  42.     /* check is any num is zero */
  43.     if( AllZero( A ) || AllZero( B ) ){
  44.         return;
  45.     }
  46.     /* normal multiplication for n lower value
  47.     limit should be power of 2 ( 16,32,64 )
  48.     any value can be used but 32 seems to b bettr */
  49.     if( n<=32 ){
  50.         for( i=0;i<n;i++ ){
  51.             for( j=0;j<n;j++ ){
  52.                 Ret[i+j] += A[i]*B[j];
  53.             }
  54.         }
  55.         return;
  56.     }
  57.  
  58.     vector<long> A1( A.begin()+n/2,A.end());
  59.     vector<long> A0( A.begin(),A.begin()+n/2 );
  60.     vector<long> B1( B.begin()+n/2,B.end());
  61.     vector<long> B0( B.begin(),B.begin()+n/2 );
  62.  
  63.     vector<long> A1_B1,A0_B0;
  64.     KaratSuva( A1,B1,A1_B1 );
  65.     KaratSuva( A0,B0,A0_B0 );
  66.  
  67.     for( i=0;i<n/2;i++ ){
  68.         A1[i] += A0[i];
  69.         B1[i] += B0[i];
  70.     }
  71.  
  72.     vector<long> A_B;
  73.     KaratSuva( A1,B1,A_B );
  74.     for( i=0;i<n;i++ ){
  75.         A_B[i] -= A1_B1[i]+A0_B0[i];
  76.     }
  77.  
  78.     for( i=0;i<n;i++ ){
  79.         Ret[i] += A0_B0[i];
  80.         Ret[i+n/2] += A_B[i];
  81.         Ret[i+n] += A1_B1[i];
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement