//分治法求a^b,因为全部过程最多是三位数在运算,所以用int完全可以存储完全。 int getPow(int a,int b){ if(b == 0){ return 1; }else if(a <= 1 || b == 1) return a %1000; else if(b == 2){ return a*a % 1000; }else if(b & 0x01 == 1){ return (getPow(getPow(a,b/2),2)*a)% 1000; }else{ return (getPow(getPow(a,b/2),2))% 1000; } }
// 正解如下:先进行边界处理,然后二分 // 细节问题:getpow不能直接强转为int double GetPow(int base, int power) { if (power == 0) return 1; if (power == 1) return base; if (power % 2 == 0) return ((int) round((pow(GetPow(base, power / 2), 2))) % 1000); else return ((int) round((pow(GetPow(base, power / 2), 2) * base)) % 1000); }
class Solution(): def lastThreeNums(self, a, b): if b == 0: return 1 if b % 2 == 0: return pow(self.lastThreeNums(a, b/2), 2) % 1000 else: return pow(self.lastThreeNums(a, int(b/2)), 2) * a % 1000