首页 > 其他分享 >lintcode: Fast Power

lintcode: Fast Power

时间:2022-12-01 19:06:14浏览次数:40  
标签:return Power int res lintcode bi long base Fast


Calculate the a^b % b where a, b and n are all 32bit integers.

Example For 231 % 3 = 2

For 1001000 % 1000 = 0

Challenge O(logn)

思路参见我的博客 ​​幂模运算​​

class Solution {
public:
/*
* @param a, b, n: 32bit integers
* @return: An integer
*/
int fastPower(int a, int b, int n) {
// write your code here
long long res=1;//用int的话中间会溢出
long long base=a;

if(n==0){
return 1%b;
}

while(n){
int bi=n%2;
n/=2;
if(bi){
res=(res*base)%b;
}
base=(base*base)%b;
}

return res;
}
};


标签:return,Power,int,res,lintcode,bi,long,base,Fast
From: https://blog.51cto.com/u_15899184/5903599

相关文章

  • lintcode:Binary Tree Serialization
    Designanalgorithmandwritecodetoserializeanddeserializeabinarytree.Writingthetreetoafileiscalled‘serialization’andreadingbackfromthe......
  • lintcode: N-Queens
    Then-queenspuzzleistheproblemofplacingnqueensonann×nchessboardsuchthatnotwoqueensattackeachother.Givenanintegern,returnalldistincts......
  • lintcode:Permutations
    Givenalistofnumbers,returnallpossiblepermutations.ChallengeDoitwithoutrecursion.1.递归classSolution{public:/***@paramnums:Alistofi......
  • lintcode:Subsets
    Givenasetofdistinctintegers,returnallpossiblesubsets.ChallengeCanyoudoitinbothrecursivelyanditeratively?1.18sclassSolution{public:/**......
  • lintcode: Permutations II
    Givenalistofnumberswithduplicatenumberinit.Findalluniquepermutations.可以见我的博文​​全排列实现​​classSolution{public:/***@paramnu......
  • lintcode: Subsets II
    Givenalistofnumbersthatmayhasduplicatenumbers,returnallpossiblesubsets1.先排序;再按求Subsets一样的做法,只是添加前检查是否已经存在。耗时171mscla......
  • lintcode:Subarray Sum Closest
    Givenanintegerarray,findasubarraywithsumclosesttozero.Returntheindexesofthefirstnumberandlastnumber.ExampleGiven[-3,1,1,-3,5],retur......
  • lintcode: Sqrt(x)
    Implementintsqrt(intx).Computeandreturnthesquarerootofx.Examplesqrt(3)=1sqrt(4)=2sqrt(5)=2sqrt(10)=3ChallengeO(log(x))求非线性方程的解可以......
  • PowerDesigner从Excel导入表(批量)
    PowerDesigner要导入Excel,需要使用到VB语法,同时PowerDesigner集成了访问Excel的方法,VB代码如下:'开始OptionExplicitDimmdl'thecurrentmodelSetmdl=ActiveMo......
  • 不支持PowerShell 2.0版本(don't support PowerShell version 2.0. )
    在“程序包管理器控制台”使用命令“update-database”会提示:TheEntityFrameworkCorePackageManagerConsoleToolsdon'tsupportPowerShellversion2.0.Upgradet......