I need to multiply two numbers in JavaScript, but I need to do without using the multiplication operator "*". Is it possible?
function a(b,c){
return b*c;
} // note:need to do this without the "*" operator
I need to multiply two numbers in JavaScript, but I need to do without using the multiplication operator "*". Is it possible?
function a(b,c){
return b*c;
} // note:need to do this without the "*" operator
Yes. Because multiplication is just addition done multiple times. Also have meaningful signatures for methods instead of using single alphabets.
function multiply(num, times){
// TODO what if times is zero
// TODO what if times is negative
var n = num;
for(var i = 1; i < times; i++)
num += n; // increments itself
return num;
}
a=(b,c)=>Math.round(b/(1/c))
round
method — I used it in order to get sane and accurate result e.g. (since 0.1 + 0.2 !== 0.3)
– daGo
Feb 11 '18 at 10:46
You need to be able to handle negatives and zeros. Other above answers don't help here. There are different ways. One relatively messy way could be ifs:
function multiply(num1, num2) {
var sum = 0;
for (var i = 0; i < Math.abs(num2); i++) {
sum += num1;
}
if (num1 < 0 && num2 < 0) {
return Math.abs(sum);
} else if (num1 < 0 || num2 < 0 ) {
return -sum;
} else {
return sum;
}
}
repeat() method of string can be used to find multiplication of two numbers.
var a = 3;
var b = 4;
console.log("c".repeat(a).repeat(b).length)
log: 12
It is repeating c, a times=> 'ccc' and then whole string b times=> 'cccccccccccc', length of the final string will be a*b;
This is similar to loop approach. This approach is limited to positive and integer numbers only.
function multiply(num1, num2) {
let num = 0;
// Check whether one or both nums are negative
let flag = false;
if(num1 < 0 && num2 < 0){
flag = true;
// Make both positive numbers
num1 = Math.abs(num1);
num2 = Math.abs(num2);
}else if(num1 < 0 || num2 < 0){
flag = false;
// Make the negative number positive & keep in num2
if(num1 < 0){
temp = num2;
num2 = Math.abs(num1);
num1 = temp;
}else{
num2 = Math.abs(num2);
}
}else{
flag = true;
}
let product = 0;
while(num < num2){
product += num1;
num += 1;
}
// Condition satisfy only when 1 num is negative
if(!flag){
return -product;
}
return product;
}
console.log(multiply(-2,-2));
Is this from some programming puzzle or interview question? :)
Since multiplication is repeated addition, you probably want a loop which adds one of the factors to the result for each count in the other factor.
function multiply(a, b) {
let answer = a
for(var i = 0; i < b - 1; i++) {
answer += a
}
return answer
}
Breakdown:
multiply(6, 3)
- our a
is 6
and b
is 3
before multiplyinganswer
is 6
//answer
is now 12
, i
is now 1
// i is now 1 answer
is now 18
, i
is now 2
i
is no longer less than (b - 1)
answer
which would be 18
$a=5;
$b=3;
for($i=0;$i<$b;$i++){
$c +=$a;
}
echo $c;
This simple and easy way in php i hope this is so easy and simple