Advertisement
sbduke73

Some of the Most Used Algorithms

Jul 15th, 2020
864
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. /*
  2.  * Title : Some of the Most Used Algorithms
  3.  * Language : C / C++
  4.  * Author: Sharif Bin Haque, Dhaka, Bangladesh
  5. */
  6.  
  7. //requires bool arr[] for storing primality (0= prime, 1= composite)
  8. void SieveOfEratosthenes (int n)
  9. {
  10.     arr[0]=arr[1]=1;
  11.     int i,j;
  12.     for (i=2;i<=n;i++) if (arr[i]==0) for (j=2;i*j<=n;j++) arr[i*j]=1;
  13. }
  14.  
  15. // arr[0<=i<=n] is predefined to be equal i
  16. void EulerPhi (ll n)
  17. {
  18.     long long i,j;
  19.     for (i=2;i<=n;i++) if (arr[i]==i) for (j=1;i*j<=n;j++) arr[i*j]-=arr[i*j]/i;
  20. }
  21.  
  22. #define ll long long
  23. ll BigMOD (ll base, ll pow, ll mod)
  24. {
  25.     ll ans=1;
  26.     while (pow>0)
  27.     {
  28.         if (pow%2==1) ans=ans%mod * base%mod, pow--;
  29.         else while (pow%2==0)base=((base%mod)*(base%mod))%mod, pow/=2;
  30.     }
  31.     return ans % mod;
  32. }
  33.  
  34. // vector<ll> fact stores factorial value of 0<=i<=n
  35. ll Fast_nCr (ll n, ll r)
  36. {
  37.     if (n==0 || r==0) return 1;
  38.     else if (r>n) return 0;
  39.     return (fact[n]*BigMOD(fact[r],M-2,M)*BigMOD(fact[n-r],M-2,M))%M;
  40. }
  41.  
  42. ll Lucas_nCr( ll a, ll b)
  43. {
  44.     if (a==0 || b==0) return 1;
  45.     else if (b>a) return 0;
  46.     ll ai=a%M, bi=b%M;
  47.     return (Fast_nCr(ai,bi)*(Lucas_nCr(a/M,b/M))%M);
  48. }
  49.  
  50. // The Following code is from GeekforGeeks
  51. long long FastPower(long long base, long long power) {
  52.     long long result = 1;
  53.     while(power > 0) {
  54.         if(power % 2 == 1) { // Can also use (power & 1) to make code even faster
  55.             result = (result*base) ;
  56.         }
  57.         base = (base * base);
  58.         power = power / 2; // Can also use power >>= 1; to make code even faster
  59.     }
  60.     return result;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement