我有一个可以计算数字平方根的函数集。我需要优化建议或有关如何加速或改进此代码的任何提示。代码如下:
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));
}
感谢大家提供的任何提示。它有很大的帮助。