鱼C论坛

 找回密码
 立即注册
查看: 3427|回复: 0

一道作业题,有关低级处理,效率,Karatsuba算法

[复制链接]
发表于 2014-7-4 17:37:18 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #define SWAP(a,b) { a ^= b; b ^= a; a ^= b; }

  5. unsigned long int karatsuba(unsigned long int a, unsigned long int b);
  6. int main () {
  7.     unsigned long int a, b;
  8.     srand(time(NULL));
  9.    
  10.    
  11. #ifndef TEST
  12.     a=rand(); b=rand();
  13.     printf("%ld*%ld=%ld\n",a,b,karatsuba(a,b));
  14. #endif
  15.    
  16. #ifdef TEST
  17.     for(int i=0; i< 1000000; i++) {
  18.         a=rand(); b=rand();
  19.         if(karatsuba(a,b)!=a*b) {
  20.             fprintf(stderr,"Error: a=%ld, b=%ld\n",a,b);
  21.             exit(-1);
  22.         }
  23.     }
  24.    
  25. #endif
  26. }

  27. unsigned long int karatsuba(unsigned long int a, unsigned long int b) {
  28.     int i, n, N;
  29.     unsigned long int x0, y0;
  30.     unsigned long int z0, z1, z2;
  31.     if(a<b) SWAP(a,b);
  32.     if(b==0) return 0;
  33.     for(n=-1, i = 1; i <= b; i<<=1, n++);  /* not optimal */
  34.     for(N=n; i <= a; i<<=1, N++);
  35.     y0=b&((1<<n)-1);
  36.     x0=a&((1<<N)-1);
  37.     z2=1<<(N-n);
  38.     z1=karatsuba(z2,y0)+x0;
  39.     z0=karatsuba(x0,y0);
  40.     return (z2<<(2*n))+(z1<<n)+z0;
  41. }
复制代码
                                                                                                                                        Explainwhat specific adjustments were made to the algorithm inorder to improve the efficiency.



                                                                                                Write an efficient function to replace the for loops marked as “notoptimal”. Hint: you can use some assembler instructions (keyword asm), some build-incompiler functions (dependent on your compiler), or the operators &, |, << and >>
                               
                       
               
                               
                       
               


题目大致意思是说这段代码用karatsuba算法在算两个数乘积,但是用了low level的处理,让解释一下它的高效在哪.
谁能解释一下那个karatsuba函数里的代码是在干些什么啊?顺便,如何改进/* not optimal */ 的地方?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-10 11:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表