[英]How to find the number of multiplications for x^63 using the exponent recursive function and how to justify it?
我如何 go 證明這個算法是 O(log n)?
public static long exponentiation(long x, int n){
if(n == 0){
return 1;
}
else if (n % 2 == 0){
x = exponentiation(x, n / 2);
return x * x;
}
else{
return x * exponentiation(x, n-1);
}
}
對方法exponentiation
的每個遞歸調用都是一個乘法步驟。 因此,您需要計算遞歸調用的數量。 有幾種方法可以實現這一點。 我選擇在方法中添加另一個參數。
public static long exponentiation(long x, int n, int count) {
if (n == 0) {
System.out.println("steps = " + count);
return 1;
}
else if (n % 2 == 0) {
x = exponentiation(x, n / 2, count + 1);
return x * x;
}
else {
return x * exponentiation(x, n - 1, count + 1);
}
}
這是對方法exponentiation
的初始調用
exponentiation(2, 63, 0);
當我運行上面的代碼時,會打印以下內容
steps = 11
您也可以使用static
計數器(無需更改函數原型):
public static long counter = 0;
public static long exponentiation(long x, int n){
if(n == 0){
return 1;
}
else if (n % 2 == 0){
x = exponentiation(x, n / 2);
counter++;
return x * x;
}
else{
counter++;
return x * exponentiation(x, n-1);
}
}
但是,您需要在每次調用 function 之前重置計數器,即設置counter = 0
。
請注意,您需要向計數器證明它在O(log(n))
中。 要證明復雜性,只需要通過查看代碼流來找到復雜性項即可。 假設T(n)
是計算x^n
的乘法次數。 因此,根據書面代碼,如果n
是偶數,則T(n) = T(n/2) + 1
,如果n
是奇數,則T(n) = T(n-1) + 1
。 現在,至少在兩個連續遞歸之一中,輸入n
是偶數。 因此,最多需要2 log(n)
才能達到n = 0
。 因為,對於每個偶數輸入,下一個輸入將減半。 因此,我們可以得出結論,該算法在O(log(n))
中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.