I need to write a function which:
Given 2 integers,it returns the product between the two given integers, beginning at num1, and excluding num2. I don't want to use a for loop.
Notes:
* The product between 1 and 4 is 1 * 2 * 3 = 6.
* If num2 is not greater than num1, it should return 0.
var output = multiplyBetween(2, 5);
console.log(output); // --> 24
What I have so far is below:
function multiplyBetween(num1, num2) {
if (isNaN(num1) || isNaN(num2)) return NaN;
if (num1 === 0 || num2 ===0) return 0;
if (num1 === num2) return 0;
if (num2 < num1){
return 0;
}
else{
while(num1<num2){
return num1 * multiplyBetween(num1 + 1, num2 )
}
}
}
What am I doing wrong?
The problem is that when you get to the base case of num1 == num2 you return 0, and then you multiply by the recursive call you multiply by 0, and end up returning 0 in all cases.
You should return 1 in that case rather than 0.
There's also no need for the while loop. First, because you return unconditionally in the loop, it it never repeats. And if it did repeat, it would repeat infinitely because the variables are never changed in the loop.
function multiplyBetween(num1, num2) {
if (isNaN(num1) || isNaN(num2)) return NaN;
if (num1 === 0 || num2 === 0) return 0;
if (num1 === num2) return 1;
if (num2 < num1) {
return 0;
}
return num1 * multiplyBetween(num1 + 1, num2)
}
console.log(multiplyBetween(2, 5));
function multiplyBetween(num1, num2) {
let total = 1;
if (num1 >= num2) {
return 0;
} for (let i = num1; i<num2;i++) {
total*=i;
} return total;
}
multiplyBetween(2, 5);
Related
Need help. Need an arrow function that expects 2 numbers as input (e.g. 1, 2)
and returns the sum of the two numbers. If anything other than 2 numbers is passed, return undefined.
Not sure where I'm going wrong on this.
const sum = (num1, num2) => {
if((num1.value !== 0)||(num2.value !== 0)){
return undefined
}
return num1 + num2
}
console.log(sum(4,4))
Just keeps returning undefined, and doesn't go to finding sum.
Use isNaN
const sum = (num1, num2) => {
if (isNaN(num1) || isNaN(num2)) {
return undefined;
}
return num1 + num2;
};
console.log(sum(4, 4));
You are trying to access a submember of a number value, not an object, so you will always get something you don't want to get.
This should work better :
const sum = (num1, num2) => {
if(isNaN(num1) || isNaN(num2)){
return undefined
}
return num1 + num2
}
console.log(sum(4,4))
You should also look what is isNaN which is a better way to check if you do receive a number or not :)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
I think what are are looking for is something like this.
const sum = (num1, num2) => {
if (typeof(num1) !== "number" || typeof(num2) !== "number")
return "undefined";
return num1 + num2;
}
Learning the basics and had this exercise:
"Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10, the surcharge is 2. The call addWithSurcharge(5, 15) should return 23."
I had put:
function addWithSurcharge(num1, num2) {
if (num1 <= 10) {
num1 += 1;
} else {
num1 += 2;
}
if (num2 <= 10) {
num2 += 1;
} else {
num2 += 2;
}
return num1 + num2;
}
Which works, but want to learn better syntax. Could something like
if (num1, num2 <= 10) {...
work? I realize can't do the || operator because it could affect the wrong num.
Put the numbers into an array instead, and iterate over the array so you don't have to repeat both the num1 and num2:
function addWithSurcharge(...nums) {
return nums.reduce((a, num) => {
if (num <= 10) {
num += 1;
} else {
num += 2;
}
return a + num;
}, 0);
}
console.log(addWithSurcharge(5, 15));
Without .reduce, the above is equivalent to:
function addWithSurcharge(...nums) {
nums.forEach((num, i) => {
if (num <= 10) {
nums[i] += 1;
} else {
nums[i] += 2;
}
});
return nums[0] + nums[1];
}
console.log(addWithSurcharge(5, 15));
You can use the conditional operator to make the if/else part more concise without bothering with reassignment, too:
const addWithSurcharge = (...nums) => (
nums.reduce(
(a, num) => a + num + (num <= 10 ? 1 : 2),
0
)
);
console.log(addWithSurcharge(5, 15));
You could also do:
function addWithSurcharge(num1, num2) {
return num1 + num2 + num1<=10?1:2 + num2<=10?1:2;
}
The num1<=10?1:2 basically means if(num1<=10){1} else{2} which works really well!
The most basic improvement is a helper function that you can call twice:
function withSurcharge(num) {
if (num <= 10) return num + 1;
else return num + 2;
}
function addWithSurcharge(num1, num2) {
return withSurcharge(num1) + withSurcharge(num2);
}
You could further shorten the if/else statement to use a conditional expression, but not much is gained by that:
return num + (num <= 10 ? 1 : 2);
One way you could do this would be to use the ternary opertator
function addWithSurcharge(num1,num2)
{
num1 += num1 <= 10 ? 1 : 2;
num2 += num2 <= 10 ? 1 : 2;
return num1 + num2;
}
console.log(addWithSurcharge(10,5));
If you use a ? when assigning a value it'll evaluate whatever is on the left hand side of the ? and either return the left hand side of the : if it's true or the right hand side if it's false.
min
<p id="q3">
junj
</p>
<script>
var minnum
function min(num1,num2,num3)
{ if (num1<num2)
{if (num1<num3)
{minnum=num1}
else {minnum=num3}
}
else if (num1>num2)
{ if (num2>num3)
{minnum=num3}
else {minnum=num2}
}
else if (num1=num2)
{ if(num1<num3)
{minnum=num1}
else {minnum=num3}
}
return minnum;
}
document.getElementById("q3").innerHTML = min(1,1,0)
;
</script>
This is the updated version of my question. Please do comment if it is sufficient to answer the question.Thanks again. Can't appreciate more.
One equals (=) is for assignment, two equals (==) is for comparison. You have two equals in your assignments like minnum == num1, and so your function returns undefined. Correcting this outputs the smallest number, as expected:
var minnum;
function min(num1, num2, num3) {
if (num1 < num2) {
if (num1 < num3) {
minnum = num1;
} else {
minnum = num3;
}
} else if (num1 > num2) {
if (num2 > num3) {
minnum = num3;
} else {
minnum = num2;
}
}
return minnum;
}
console.log(min(1, 2, 3));
However, it's also worth mentioning that the largest is 3, which is not the same as the minimum. This would be the maximum value, and to obtain this, simply invert all of the comparison signs:
var minnum;
function min(num1, num2, num3) {
if (num1 > num2) {
if (num1 > num3) {
minnum = num1;
} else {
minnum = num3;
}
} else if (num1 < num2) {
if (num2 < num3) {
minnum = num3;
} else {
minnum = num2;
}
}
return minnum;
}
console.log(min(1, 2, 3));
Note that it may also be worth changing the function name to something like max() to avoid confusion.
If you want minimum number from array which has no fixed length
try this
function min(numarray)
{
numarray.sort(function(a, b){return a-b}); //sort the array in
return numarray[0]; //the first number in your array is minimum number
}
var numberArray=[3,1,2,7];
console.log(min(numberArray))
//document.getElementById("q3").innerHTML = min(numberArray);
Jsfiddle Link
https://jsfiddle.net/pg4abkx7/
I have the following code, trying to return the range between two numbers, and the inner function is not returning a value. It simply returns [Function]. Can anyone tell me why?
var range = function(num1, num2) {
var output = [];
return function range2 () {
if (num2 - num1 === 2) {
return [num1+1];
}
else if (output.length + 1 === num2 - num1) {
return output;
}
else if (output.length + 1 !== num2 - num1) {
output.push(num1 + 1);
}
return range2(num1 + 1, num2);
};
};
//UPDATE: This is my code that ended up working, FWIW:
var range = function(num1, num2) {
var list = [];
var range2 = function(num1, num2) {
list.push(num1 + 1);
if (num2 - num1 === 2) {
return list;
}
else {
return range2(num1 + 1, num2);
}
};
return range2(num1, num2);
};
Your return will return the definition. If you are trying to return the execution of the function you will need to add a ()
See here:
var range = function(num1, num2) {
var output = [];
return function range2 () {
if (num2 - num1 === 2) {
return [num1+1];
}
else if (output.length + 1 === num2 - num1) {
return output;
}
else if (output.length + 1 !== num2 - num1) {
output.push(num1 + 1);
}
return range2(num1 + 1, num2);
}(); // <---- this will execute the defined function.
};
The range() function never calls range2(). It simply returns the function expression.
Also, range2() needs to take arguments.
var range = function(num1, num2) {
var output = [];
function range2(num1, num2) {
if (num2 - num1 === 2) {
return [num1 + 1];
} else if (output.length + 1 === num2 - num1) {
return output;
} else if (output.length + 1 !== num2 - num1) {
output.push(num1 + 1);
}
return range2(num1 + 1, num2);
};
return range2(num1, num2);
};
alert(range(1, 10));
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))
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;
}
}
There is another simpler mathematical approach. Let's do this in C++:
double mult(double a, double b) {
return exp(log(a) + log(b));
}
The log() function in C++ returns the natural logarithm (base-e logarithm) of the argument passed in the parameter. (arguments can be any numeric type)
The exp() function in C++ returns the exponential (Euler's number) e (or 2.71828) raised to the given argument.
When you simplify the above statement, you eventually end up with a * b, but still there is no * sign.
*You need make sure both a and b are positive, otherwise you will get nan :(
Here is a math trick
function multiply(num1, num2) {
return num1/(1/num2);
}
console.log(multiply(5,22))
I think this can be solved using recursion. Sorry for the improper indentations.
We are given 2 numbers to multiply and multiplying m with n simply means adding m, n times.
if n becomes 0, return 0. This is our base case.
else
return m + multi(m,n-1)
we are returning m every time, because we need to add m up to n times
In every call we are decreasing the n's value so as the n becomes 1, we'll call it for the last time.
function multi (int m, int n){
if(n === 0)
return 0;
return m + multi(m,n-1);
}
repeat() method of string can be used to find multiplication of two numbers.
var a = 3;
var b = 4;
var res = "1".repeat(a).repeat(b).length;
console.log(res)
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));
function multiple(a, b) {
let sum = 0;
for (let i = 0; i < Math.abs(b); i++) {
sum += Math.abs(a);
}
if (a < 0 && b < 0) {
return Math.abs(sum);
} else if (a < 0 || b < 0 ) {
return -sum;
} else {
return sum;
}
}
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.