我正在做作業,我必須用exponentiation by squaring來做兩件事。一個是獲得乘法的數量,另一個是獲得實際結果。通過平方運算求冪(得到乘法運算的次數)
下面是一些例子:
2
11
應該輸出
2048
5
因爲2^11 = 2(2((2)²)²)²
我這樣做沒有遞歸和我得到的結果正確的,但數量乘法是錯誤的。如果我輸入2^6
我得到3
乘法,這是行,但如果我輸入2^8
我得到4
乘法,這是錯誤的。
你能指出我在做什麼錯誤,以獲得正確的乘法涉及?
下面是代碼:
public static void main(String[] args) {
double x, result = 1;
int n, multiplications = 0;
DecimalFormat df = new DecimalFormat("#.00");
Scanner readLine = new Scanner(System.in);
x = readLine.nextDouble();
n = readLine.nextInt();
if (n == 1) {
multiplications++;
System.out.print(df.format(x) + "\n" + multiplications + "\n");
} else if (n == 2) {
x *= x;
multiplications++;
System.out.print(df.format(x) + "\n" + multiplications + "\n");
} else {
while (n > 0) {
if (n % 2 == 0) {
multiplications++;
} else {
multiplications++;
result *= x;
n--;
}
x *= x;
n /= 2;
}
System.out.print(df.format(result) + "\n" + multiplications + "\n");
}
}
我沒有得到乘法部分。你是如何得到這個輸出的?以及如何根據括號的順序和位置獲得任何其他輸出? – 2013-02-17 10:07:29
請參閱我通過平方排列在指數上的鏈接。乘法部分沒有按預期工作,所以這是問題。 – Favolas 2013-02-17 10:17:24