繁体   English   中英

简单Java代码的时间复杂度

[英]Time complexity of the simple java code

如何确定此代码的时间复杂度? 我猜想modPow方法是最“昂贵”的。

import java.math.BigInteger;    
public class FermatOne    
{    
    public static void main(String[] args)    
    {    
         BigInteger a = new BigInteger ("2");    
         BigInteger k = new BigInteger ("15");    
         BigInteger c = new BigInteger ("1");    
         int b = 332192810;    
         BigInteger n = new BigInteger ("2");    
         BigInteger power;    
         power = a.pow(b);    
         BigInteger exponent;    
         exponent = k.multiply(power);    
         BigInteger mod;    
         mod = exponent.add(c);    
         BigInteger result = n.modPow(exponent,mod);    
         System.out.println("Result is  ==> " + result);    
     }    
}

好吧,这个特定的代码确定地在O(1)运行。

但是,从更笼统的意义上讲,任意变量的multiply()将在O(nlog n)中运行,其中n是位数。

对于小ab pow()方法将在O(log b)运行。 这是通过对平方求幂来实现的。 对于较大的值,位数(线性)变大,因此乘法需要更多时间。 我将由您自己决定确切的分析。

我不是100%关于modPow()的细节,但我怀疑它的运行方式与pow()相似,只是在平方运算的每个步骤中都有额外的mod 因此仍然是O(log b)乘法,其附加好处是位数由log m限制,其中m是mod。

tskuzzy是正确的。

但是,也许您需要仔细阅读这两行,并假设这是一个家庭作业问题,他们可能希望您意识到这种方法中发生的几种操作具有不同的复杂性。 然后他们可能希望您认识到整个方法的复杂性与方法中发生的最复杂的操作相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM