gpt4 book ai didi

java - 无符号乘法求和算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:23:20 34 4
gpt4 key购买 nike

我正在尝试在 Java 中创建一个算法来进行无符号乘法。然后,该算法使用无符号和。这是代码:

public int[] unsignedSum(int[] n1, int[] n2){
int[] result = new int[48];
int carry = 0;
for(int x = 47; x >= 0; x--){
if (n1[x]+n2[x]+carry == 1){
result[x] = 1;
carry = 0;
}
else if (n1[x]+n2[x]+carry == 2)
carry = 1;
else if (n1[x]+n2[x]+carry == 3)
result[x] = 1;
}
return result;
}
public int[] unsignedMult(int[] n1, int[] n2){
int[] result = new int[48];
int[] N1 = new int[48];
int[] N2 = new int[48];
//fix the size to 48
for (int x = 24; x < 48; x++){
N1[x] = n1[x-24];
N2[x] = n2[x-24];
}
for(int x = 47; x >= 0; x--){
if (N2[x] == 1){
int[] shiftedN1 = new int[48];
for (int y = 0; y < x; y++)
shiftedN1[y] = N1[y+48-x];
result = unsignedSum(result, shiftedN1);
}
}
return result;
}

vector n1 和 n2 的大小为 24
任何其他 vector 的大小为 48
问题是:在某些情况下它会吃掉第一个数字。
乘法不应该溢出,但在这种情况下,它会以某种方式溢出。
1100000...(24 位)* 1100000(24 位).. 应该导致 10010000...(48 位),但它导致 00100000...(48 位)

最佳答案

中查找 2 个差一错误
for (int y = 0; y < x; y++)
shiftedN1[y] = N1[y+48-x];

What is exactly the off-by-one errors in the while loop?

您可能希望使用简单的 ....0001 * ....0001 手动运行上述循环

关于java - 无符号乘法求和算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29725973/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com