Advertisement
LinKin

FFT

May 26th, 2013
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. /*
  2.  * Algorithm : Fast Fourier Transform
  3.  * Order : O( Nlog )
  4.  */
  5. #include<stdio.h>
  6. #include<string.h>
  7. #include<math.h>
  8. #include<vector>
  9. #include<algorithm>
  10. #include<complex>
  11. using namespace std;
  12.  
  13. typedef vector<long> VL;
  14. typedef complex<double> CN;
  15. const double PI = 2*acos( 0.0 );
  16.  
  17. void FFT( vector<CN> &a, bool invert ){
  18.     long i,j,n = a.size();
  19.     for( i=1,j=0;i<n;i++ ){
  20.         long bit = n >> 1 ;
  21.         for( ;j>=bit;bit>>=1 ) j -= bit ;
  22.         j += bit ;
  23.         if( i < j ) swap( a[i],a[j] );
  24.     }
  25.     long len;
  26.     for( len=2;len<=n;len<<=1 ){
  27.         double ang = 2*PI / len * ( invert ? -1:1 );
  28.         CN wlen( cos( ang ) , sin( ang ) );
  29.         for( i=0;i<n;i+=len ){
  30.             CN w( 1 ) ;
  31.             for( j=0;j<len/2;j++ ){
  32.                 CN u = a[i+j] , v = a[i+j+len/2]*w;
  33.                 a[i+j] = u+v; a[i+j+len/2] = u-v; w *= wlen;
  34.             }
  35.         }
  36.     }
  37.     if( invert ){
  38.         for( i=0;i<n;i++ ) a[i] /= n;
  39.     }
  40. }
  41.  
  42. void Multiply( const VL &a, const VL &b, VL &res ){
  43.     vector<CN> fa( a.begin(),a.end() ), fb( b.begin(),b.end() );
  44.     long i,n = 1 ;
  45.     while( n < max( a.size(),b.size()) ) n <<= 1;
  46.     n <<= 1;
  47.     fa.resize( n ),fb.resize( n );
  48.     FFT( fa,false ) , FFT( fb,false );
  49.     for( i=0;i<n;i++ ) fa[i] *= fb[i];
  50.     FFT( fa,true );
  51.     res.resize( n );
  52.     for( i=0;i<n;i++ ) res[i] = long( fa[i].real() + 0.5 );
  53.     /* if multiplication between 2 number then res need to be mod by 10 */
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement