私は宿題をやっています.squaringによるべき乗を使用して2つのことをしなければなりません. 1 つは乗算の数を取得することで、もう 1 つは実際の結果を取得することです。
以下にいくつかの例を示します。
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");
}
}