题目:四个正整数ABCD,均小于10000。写一个函数实现D等于A的B次方与C取余。
代码一:
int function(int a,int b,int c)
{
int s = 1;
for(int i = 0 , i < b , i++)
{
s = s*(a%c)%c
}
return s;
}
代码二:
unsigned int fact( unsigned int a,unsigned int b,unsigned int c )
{
unsigned int d=1;
int u=31;
for( ; u>=0 ; --u )
{
d=d*(d%c);
if( b & ( 1<< u ) )
{
d=d*(a%c);
}
}
return d;
}
代码三:
int solve(int a,int b,int c)
{
int s = 1;
while(b)
{
if(b & 1)
s = (s % c)* (a %c) % c;
a = (a * a) % c;
b >>= 1;
}
return s;
}
不同的三个人写出不同的代码,从代码的结果来看,都实现了题目要求的功能。可是,却展现了三个人不同的代码水平!
你谁是第几种?甚至会写出更优的代码呢?
如有更优的代码,请附带!