如何在不使用*
的情况下获取两个整数的乘积我试图找出在我的解决方案中不使用*就可以得到两个整数乘积的方法。我得到的最接近的是如何在不使用*
/*Example: 2,5 output ====> 10 */
/*Example: 10,5 output ====> 50 */
const productOfTwoInt = (int,int2) => {
var data1 = 0;
var data2 = 0;
var result;
var result2;
for(var x = 0; x <= int; x++) {
result = x += data1
console.log(result)
}
for(var j = 0; j <= int2; j++) {
result2 = j += data2
}
return result + result2
}
console.log(productOfTwoInt(3,5))
您的解决方案已经相当不错了。这可有点简化为:
function multiply(a,b){
//just one minus, lets swap
if(a<0 && b>0) [a,b] = [b,a];
//two minuses: let them be positive
if(a<0 && b<0) (a = Math.abs(a), b = Math.abs(b));
var result = 0;
while(a--){
result += b;
}
return result;
}
console.log(
multiply(1,2),
multiply(3,4),
multiply(6,7),
multiply(-1,-2),
multiply(1,-2)
);
如果'a'是负数,你会得到一个无限循环。 – Amy
@amy jup固定... –
你可以做
const productOfTwoInt = (x, y) => {
let z = Math.log(x) + Math.log(y);
return Math.round(Math.exp(z));
}
console.log(productOfTwoInt(3,5))
聪明,但只会对正整数有效。试试'productOfTwoInt(-2,5)'。 – dfsq
正如尼娜肖尔茨的answer, “俄罗斯乘法” 建议:
const productOfTwoInt = (a, b) => {
var a0 = a;
var result = 0;
while (1) {
if (a0 % 2 !== 0)
result += b;
if (a0 == 1 || a0 == -1) break;
a0 = Math.floor(a0/2);
b *= 2;
}
\t \t return a > 0 ? result : -result;
}
console.log(
productOfTwoInt(4, 5),
productOfTwoInt(4, -5),
productOfTwoInt(-40, 5),
productOfTwoInt(-4, -50)
);
传统的解决方案:
const productOfTwoInt = (int, int2) => {
let result = 0;
let isPositive = int > 0;
let i = 0;
while (i != int) {
result += int2;
if (isPositive)
i++;
else
i--;
}
\t return isPositive ? result : -result;
}
console.log(
productOfTwoInt(4, 5),
productOfTwoInt(4, -5),
productOfTwoInt(-4, 5),
productOfTwoInt(-4, -5)
);
你可以采取一些位转移,被称为ancient egyptian multiplication或russian multiplication。
a b p comment ---- ---- ---- ---------------------------------- 6 8 0 skip, because a is even 3 16 16 add 16 to p, because a is odd 1 32 48 add 32 to p, because a is odd 0 64 48 stop iteration, because a is zero
function product(a, b) {
var p = 0;
while (a) {
p += (a & 1) && b;
a >>= 1;
b <<= 1;
}
return p;
}
console.log(product(6, 8)); // 48
不错的一个;)如何负数? –
@Jonasw,你把标志存储起来,稍后再应用。 –
你可以用它做这样
选项1
function mul(m,n){
// make it more efficient
if(m<n)
{
var temp =m;
m=n;
n=temp;
}
var v=0;
if(n==1)
return m;
v = mul(m,n>>1);
v = v+v;
if(n&1)
v+= m;
return v;
}
console.log(mul(-2,5));
你可以用逆像这样做:
function multiply(a, b) {
return a/(1/b)
}
multiply(2, 5) // 10
multiply(10, 5) // 50
'的(VAR I = 0;我
shmosel