[英]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
是位數。
對於小a
和b
pow()
方法將在O(log b)
運行。 這是通過對平方求冪來實現的。 對於較大的值,位數(線性)變大,因此乘法需要更多時間。 我將由您自己決定確切的分析。
我不是100%關於modPow()
的細節,但我懷疑它的運行方式與pow()
相似,只是在平方運算的每個步驟中都有額外的mod
。 因此仍然是O(log b)
乘法,其附加好處是位數由log m
限制,其中m
是mod。
tskuzzy是正確的。
但是,也許您需要仔細閱讀這兩行,並假設這是一個家庭作業問題,他們可能希望您意識到這種方法中發生的幾種操作具有不同的復雜性。 然后他們可能希望您認識到整個方法的復雜性與方法中發生的最復雜的操作相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.