Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <time.h>
  4.  
  5. unsigned long long multiple_karatsuba(unsigned long long x, unsigned long long y);
  6. int number_of_bits (unsigned long long x);
  7.  
  8. int main()
  9. {
  10.     srand(time(NULL));
  11.     int size = 100;
  12.     printf("Karatsuba\n");
  13.    
  14.     clock_t begin_time = clock();
  15.    
  16.     for(int i = 0; i < size; i++) {
  17.         unsigned long long x = rand() % 20000000 + 1000000;
  18.         unsigned long long y = rand() % 20000000 + 1000000;
  19.        
  20.         //printf("%lu * %lu = %lu\n", x, y, multiple_karatsuba(x, y));
  21.         printf("%lu * %lu = %lu\n", x, y, x * y);
  22.     }
  23.    
  24.     clock_t end_time = clock();
  25.    
  26.     printf("Execution time with %d multiplications: %f", size, (end_time - begin_time)/CLOCKS_PER_SEC);
  27.    
  28.     return 0;
  29. }
  30.  
  31. unsigned long long multiple_karatsuba(unsigned long long x, unsigned long long y) {
  32.     if (x < 10 && y < 10)
  33.         return x * y;
  34.        
  35.     int n = 0;
  36.    
  37.     if(number_of_bits(x) > number_of_bits(y)) {
  38.         n = number_of_bits(x);
  39.     } else {
  40.         n = number_of_bits(y);
  41.     }
  42.    
  43.     int m = n / 2 + n % 2;
  44.    
  45.     long a = x / (long) pow(10, m);
  46.     long b = x % (long) pow(10, m);
  47.     long c = y / (long) pow(10, m);
  48.     long d = y % (long) pow(10, m);
  49.    
  50.     long step1 = multiple_karatsuba(a, c);
  51.     long step2 = multiple_karatsuba(b, d);
  52.     long step3 = multiple_karatsuba(a + b, c + d);
  53.     long step4 = step3 - step2 - step1;
  54.    
  55.     long step5 = step1 * (long) pow(10, m * 2) + step2 + step4 * (long) pow(10, m);
  56.    
  57.     return step5;
  58. }
  59.  
  60. int number_of_bits (unsigned long long x) {
  61.     int counter = 0;
  62.     while(x) {
  63.         counter++;
  64.         x /= 10;
  65.     }
  66.     return counter;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement