1. Assume that your CPU does not have multiply and divide units. You can not use function in C that will not use multiply, divide and modulo operators. Write the following programs:
a) multiply any given number by 7
b) divide any given number by 7
2. Make sure that you write the most optimized code, and give full description of any potential errors that can happen using your function.
For 1(a)
typedef ElemType int;
#define NUM 7;
ElemType Multiply(ElemType Num,ElemType n)
{
ElemType Result;
for(int i=0;i<NUM;i++)
{
Result +=n;
}
return Result;
}
then the result is NUM*n,but this methord is not good,as it's not fast,lets try another one;
ElemType Multiply(ElemType NUM,ElemType n)
{
ElemType Result,n1,n2;
n1=n<<3; //that's n1=n*8;
n2=n; //that's n2=n*1;
Result=n1-n2; //that's Reuslt=n*8-n*1=7*n;
return Result;
}
For 1(b),it's the same
这个方法有点难想出来.
尤其是在做除法的时候.
果然厉害