How to check if number is even using recursive function in JavaScript - javascript

I am trying to do an exercise from here https://www.w3resource.com/javascript-exercises/javascript-recursion-function-exercise-7.php
I understand the solution, however, I am kind of curious why my program does not yield the same answer as above. The way I choose the return the function is slightly different, however, it yields a number instead of true or false.
function checkeven(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
console.log(num);
return num - checkEven(num - 2);
}
}
console.log(checkeven(8));
console.log(checkeven(9));

In JavaScript - when the operands to an operator are of different types - type corecion happens, i.e it tries to convert one of the operands into a type that is compatible with the operator
Try this:
console.log(2 + true) //3
console.log(true + false) //1
In your case, consider what happens when you try checkeven(2)
checkeven(2) = 2 - checkeven(0) = 2 - true = 1

Replace return num - checkeven(num - 2) with return checkeven(num - 2) in your code.
function checkeven(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
return checkeven(num - 2);
}
}
console.log(checkeven(8));
console.log(checkeven(9));

Concocted a solution with both positive and negative numbers!
var isEven = function (n) {
if (n > 0) {
return positive(n);
} else {
return negative(n);
}
function negative(num) {
if (num === 0) {
return true;
} else if (num === -1) {
return false;
} else {
return isEven(num + 2);
}
}
function positive(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
return isEven(num - 2);
}
}
};
console.log(isEven(9));
console.log(isEven(8));
console.log(isEven(-8));

your code had issue since you we trying to subtract from a boolean value , Due to which type corecion occurs as per the rules given under ecmascript guidlines.(https://www.ecma-international.org/ecma-262/7.0/#sec-ordinary-and-exotic-objects-behaviours)
you can go with the following solution:
(function fixthis() {
function checkeven(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
let Tempnum = num - 2;
if (checkeven(Tempnum)) {
return true;
} else {
return false;
}
}
}
console.log(checkeven(8));
console.log(checkeven(9));
})()

return checkeven(num-2);, returns a boolean value. You are trying to subtract a boolean value from a number, which won't work. Your code will work just fine if you remove num-checkeven(num-2)* and replace it with checkeven(num-2);

You can do:
odd = function(n) {if (n%2 == 0) {return true} else {return false;}}
console.log(odd(8));
console.log(odd(5));
or:
checkeven = function(num) {
if (num === 0) {
return true;
} else if (num === 1) {
return false;
} else {
return checkeven(num - 2);
}
}
console.log(checkeven(8));
console.log(checkeven(9));

You can also use the modulo operator, so you don't even need recursion
const areYouEven = n => !(n % 2)

Related

How to return NaN

I'm working on a codewars problem-here's the question:
-Write a function that accepts two integers and returns the remainder of dividing the larger value by the smaller value.
-Division by zero should return NaN.
I have the first part figured out, but how do I return NaN if I divide by 0? I don't know a lot about NaN and I'm pretty new to JavaScript.
function remainder(n, m){
if (n > m) {
let answer = n % m;
if (m === 0) {
return undefined;
}
else {
return answer;
}
}
else if (m > n) {
let answer = m % n;
if (n === 0) {
return undefined;
}
else {
return answer;
}
}
else {
let answer = n % m;
return answer;
}
}
Edit: solved, answer is below
Welcome to our community!
NaN stands for Not-a-Number and it is a property of the global object(in order to understand more about the global object, I would recommend reading about Scopes).
You could access NaN like this:
window.NaN => from a browser
Number.NaN
NaN
If you want to check if a number is NaN you could use: isNaN.
If you want to use it in a function you can just do
function test(x){
if(isNaN(x)){
return NaN;
}
return x;
}
To come back to your problem, you could do something like this:
function calculateRemainder(a,b){
return a>b ? a % b : b % a
}
Where % is known as the remainder operator about which you can read more here. This operator returns NaN if you try to divide by 0 or to operate with Infinity.
The following operations return NaN:
NaN % 2
Infinity % 0
10 % 0
Infinity % Infinity
The problem is that % is not the divider syntax, but this is /.
I created a basic example for you:
In this example, the console logs "divider is 0"
function divider(up, down) {
if (down == 0) {
console.log("divider is 0");
return NaN
} else {
console.log(up / down);
}
}
divider(5, 0);
But here, it will log 2.5
function divider(up, down) {
if (down == 0) {
console.log("divider is 0");
return NaN
} else {
console.log(up / down);
}
}
divider(5, 2);
This is my answer (with help from the comments on my question), and it worked. Thank you for your help!
function remainder(n, m){
if (n > m) {
let answer = n % m;
if (m === 0) {
return NaN;
}
else {
return answer;
}
}
else if (m > n) {
let answer = m % n;
if (n === 0) {
return NaN;
}
else {
return answer;
}
}
else {
let answer = n % m;
return answer;
}
}

isNan help in an if else statement

I am doing an online exercise and I am required to use an if else statement. The isNaN statement is not working. I am required to return a string if the input of number is not an actual number. This won't compile please help:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else if (number % 2 !== 0) {
return false;
} else if (isNaN(number)) {
return "you need to enter a number";
} else {
return false;
}
};
Your code returns false because of
else if (number % 2 !== 0)
line, So check isNaN before everything like so
var isEven = function(number) {
if (isNaN(number)) {
return "you need to enter a number";
} else {
if (number % 2 === 0){
return true;
} else if (number % 2 !== 0) {
return false;
}
}
};
console.log(isEven(NaN));
you need to enter a number
You need to have isNan as first check in you if-else-if condition.
Explanation:
If the argument is not a number, then number % 2 !== 0 will be true and it will return the value.
Note:
return statement, terminates the execution of the function further and returns the value. So, even if-else-if is not required here.
and beware with Booleans in NaN and empty string.
Example Snippet:
var isEven = function(number) {
if (isNaN(number)) {
return "you need to enter a number";
}
if (number % 2 === 0) {
return true;
} else {
return false;
}
};
console.log(isEven(2));
console.log(isEven(3));
console.log(isEven('i am not a number'));
console.log(isEven(true));

ES6 javascript constant-return error

running lint on a test module is stating an error :
module.exports = (x) => {
if (x % 2 === 0) {
return 'even';
} else if (x % 2 === 1) {
return 'odd';
} else if (x > 100) {
return 'big';
} else if (x < 0) {
return 'negative';
}
};
running ESLint :
> yarn lint
../server/modules/my-awesome-module.js (1/0)
✖ 3:22 Expected to return a value at the end of this function consistent-return
✖ 1 error (7:35:56 PM)
error Command failed with exit code 1.
what is the correct ES6 coding in this case ?
thanks for feedback
You don't have an else case. If none of your if or else if conditions are met, there is no return value.
You could easily add a default else block or just a simple return at the end of the function.
The problem is that based on some code paths (any of the if/else clauses), a value might be returned by the function. however, in cases where none of the cases match (for example, where x=50.5), nothing is returned. For consistency purposes, something should be returned by the function.
An example solution would be:
module.exports = (x) => {
if (x % 2 === 0) {
return 'even';
} else if (x % 2 === 1) {
return 'odd';
} else if (x > 100) {
return 'big';
} else if (x < 0) {
return 'negative';
}
return 'none'
};
You can consider changing the code snippet as
module.exports = (x) => {
var result = "";
if (x % 2 === 0) {
result = "even";
} else if (x % 2 === 1) {
result = "odd";
} else if (x > 100) {
result = "big";
} else if (x < 0) {
result = "negative";
}
return result;
};
Hope it helps

What makes this simple recursion not work?

the First one doesn't work, its just trying to find a factorial, it returns NaN, so why is it if you use else if it doesnt work?
function FirstFactorial(num) {
if (num == 0) {
return 1;
}
else if (num > 1) {
return num * FirstFactorial(num - 1);
}
}
console.log(FirstFactorial(3)) === NaN
function factorial(n) {
if(n == 0) {
return 1
}
else {
return n * factorial(n - 1);
}
}
console.log(factorial(3)) == 6
You're missing a case for num === 1, so when you do
function FirstFactorial(num) {
if (num == 0) {
return 1;
}
else if (num > 1) {
return num * FirstFactorial(num - 1);
}
}
FirstFactorial(3);
You're doing
3 * FirstFactorial(2);
3 * 2 * FirstFactorial(1);
3 * 2 * undefined; // NaN
Re-arrange the function logic thus
function FirstFactorial(num) {
if (num > 1) {
return num * FirstFactorial(num - 1);
}
return 1;
}

Function supposed to return a boolean returns undefined

Trying to come up with a function to check if a number is prime and I'm running into trouble. I'm sure there's a simpler way to do this, but why would this function not return false, for the number 9? It returns false for even numbers but for any other type of composite number it returns undefined, but since it prints NOT PRIME it should also be returning false.
function isPrime(n, i) {
document.writeln(i);
var nextNum = i + 1;
var number = n;
if (i < n) {
if ((n % i) === 0) {
document.writeln("NOT PRIME");
return false;
} else {
document.writeln(nextNum);
isPrime(number, nextNum);
}
} else if (i === n) {
document.writeln("Recursion ends");
return true;
} else {
document.writeln("Confused" + typeof i + typeof n);
}
}
You need to return the value of the recursive call, i.e., change
isPrime(number, nextNum);
to
return isPrime(number, nextNum);
You are missing a return in this branch after the recursive call to isPrime:
if ((n % i) === 0) {
document.writeln("NOT PRIME");
return false;
} else {
document.writeln(nextNum);
isPrime(number, nextNum);
}
I think that you want to change it to:
if ((n % i) === 0) {
document.writeln("NOT PRIME");
return false;
} else {
document.writeln(nextNum);
return isPrime(number, nextNum);
}
Because you aren't returning anything in that branch, the true/false calls are disappearing.
It should just need one parameter to check if prime.
Try this out:
function isPrime(num){
// An integer is prime if it is not divisible by any prime less than or equal to its square root
var squareRoot = parseInt(Math.sqrt(num));
var primeCountUp = function(divisor){
if(divisor > squareRoot) {
// got to a point where the divisor is greater than
// the square root, therefore it is prime
return true;
}
else if(num % divisor === 0) {
// found a result that divides evenly, NOT prime
return false;
}
else {
// keep counting
return primeCountUp(++divisor);
}
};
// start # 2 because everything is divisible by 1
return primeCountUp(2);
}
Adding the high of the "square root" from here

Categories