Optimization Sqrt函数需要优化建议

Optimization Sqrt函数需要优化建议,optimization,Optimization,我有一个函数集,可以计算一个数的平方根。我需要优化建议或任何关于如何加快或改进此代码的提示。代码如下: unsigned char ACountDigits(int v){ unsigned char r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4

我有一个函数集,可以计算一个数的平方根。我需要优化建议或任何关于如何加快或改进此代码的提示。代码如下:

unsigned char ACountDigits(int v){
unsigned char r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 : 
(v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 : 
(v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
return r+1;
}

unsigned int ASqrt_LastDeduction(unsigned int x, unsigned int y){
unsigned int result = 10*y;

if(x<4+10*y*2) {
    result += 1;
} else if(x<9+10*y*3) {
    result += 3;
} else if(x<16+10*y*4) {
    result += 5;
} else if(x<25+10*y*5) {
    result += 7;
} else if(x<36+10*y*6) {
    result += 9;
} else if(x<49+10*y*7) {
    result += 11;
} else if(x<64+10*y*8) {
    result += 13;
} else if(x<81+10*y*9) {
    result += 15;
} else if(x<100+10*y*10) {
    result += 17;
}
return result;
}   

unsigned char ASqrt_Remainder(unsigned char num, unsigned char lastDeduction, unsigned char y){
return num-(((lastDeduction+1-10*y)/2)*((lastDeduction+1-10*y)/2)+10*y*(lastDeduction-10*y+1)/2);
}

double ASqrt(int whole, int decim){
int wdgcn = ACountDigits(whole);
int ddgcn = ACountDigits(decim);
unsigned char wgrp[(int)(wdgcn/2)+1];
unsigned char dgrp[(int)(ddgcn/2)+1];
int i = 0;

for (i=(int)(wdgcn/2);i>=0;i--) {
    wgrp[i] = whole % 100;
    whole /= 100;
}

for (i=0;i<=(ddgcn/2);i++) {
    dgrp[i] = decim % 100;
    decim /= 100;
}

unsigned int  lastDeduction = 0;
unsigned char deductions    = 0;
unsigned int  remainder     = 0;
unsigned int  y             = 0;
unsigned int  tempInt       = wgrp[0];
unsigned int  wRoot         = 0;

for (i=0;i<=(wdgcn/2);i++) {
    lastDeduction = ASqrt_LastDeduction(tempInt,y);
    deductions    = (lastDeduction+1-10*y)/2;
    remainder     = ASqrt_Remainder(tempInt,lastDeduction,y);
    wRoot         = wRoot*10+deductions;
    y             = lastDeduction+1;
    tempInt       = 100*remainder+wgrp[i+1];
}

tempInt       = 100*remainder+dgrp[0];
lastDeduction = ASqrt_LastDeduction(tempInt,y);
deductions    = (lastDeduction+1-10*y)/2;
remainder     = ASqrt_Remainder(tempInt,lastDeduction,y);

return (double)(wRoot + deductions/10 + remainder/(lastDeduction+1));
}

谢谢你们提供的任何提示。这很有帮助。

只是猜测。。。。从2到10的for循环?您能否指定您的目标:改进此代码但保持其基本原理,或者真正编写一个有效的平方根算法?首先,使用基数2而不是基数10将简化很多事情,并提供显著的加速。特别是,它将避免那些长链的顺序测试。如果您想保持基数10,请考虑二分法搜索树。