How to return NaN - javascript

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;
}
}

Related

Float to String Conversion - JS

So I am currently working on that function
const countSixes = n => {
if (n === 0) return 0;
else if (n === 1) return 1;
else n = (countSixes(n-1) + countSixes(n-2)) / 2;
return n;
}
And so my question is how to convert the final floating-point value into a string?
Every time after calling the function and trying to convert the float number it returns NaN
What I've Tried
"" + value
String(value)
value.toString()
value.toFixed(2)
Hope to get the answer
Thank you!
The first option works for me
<script>
const countSixes = n => {
if (n === 0) return 0;
else if (n === 1) return 1;
else n = (countSixes(n-1) + countSixes(n-2)) / 2;
return n;
}
alert(countSixes(12) + "")
</script>
The problem is really interesting. Its return NaN because when you return n as String, as the function is called recursively so it cannot perform arithmetic operations in next level.
It will never end for certain numbers like 55
function countSixes(n,firstTime=true){
if (n === 0) return 0;
else if (n === 1) return 1;
else n = (countSixes(n-1,false) + countSixes(n-2,false)) / 2;
if(firstTime) return n.toFixed(10); // return string
else return parseFloat(n.toFixed(10)); // return float
}
You could convert the final value to a string with the wanted decimals.
const countSixes = n => {
if (n === 0) return 0;
if (n === 1) return 1;
return (countSixes(n - 1) + countSixes(n - 2)) / 2;
}
console.log(countSixes(30).toFixed(15));

How to check if number is even using recursive function in 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)

How does a negative value turn positive by calling it negative in the console?

i used Math.abs but I fail and found this solution, I am following on eloquent javascript and how did negative value is turned to positive, here is the code:
function isEven(n) {
if (n == 0) {
return true;
}
else if (n == 1) {
return false;
}
else if (n < 0) {
console.log(-n);
return isEven(-n); // turn -3 to 3?
}
else {
return isEven(n - 2);
}
}
console.log(isEven(-3));
Here you are a simpler test case:
> console.log( -(-3) );
3
This is not a JavaScript peculiarity, it's how maths work.
Console has nothing to do with this.
Think back to your math class. -n is a shortened expression for (-1) * n. If you multiply two negative numbers, the result is a positive number - and since you're multiplying by negative 1 (where positive 1 is identity for multiplication), the result is the same number, but positive.
Since you're checking if (n < 0) before you multiply by -1, you'll always get a positive number.
However, this is almost definitely not what you want - the code you found seems to be an example of how to use recursion to solve common problems. In real-world Javascript, you'd want something more like this:
function isEven(x)
{
return (Math.abs(x) % 2) === 0;
}
it has to be recursion
Lets break the mold! Using -1 instead of 2. Assuming an integer;
function isEven(x) {
if (x === 0) return 1; // ended
return -1 * (isEven(Math.abs(x) - 1) ? 1 : -1) === 1;
}
Other fun ways to test for even that don't need 2 or mod/remaineder
function isEven(x) {
return Math.round(Math.sin(5 * x / Math.PI)) === 0;
}
An O(log n) recursion
function isEven(x, a) {
if (!a) a = [true, false];
if (a.length > x) return a[x];
return isEven(x, a.concat(a));
}

Understanding negative numbers in recursion

I'm just getting my head around recursion in javascript using the book Eloquent Javascript but don't fully understand what is happening to the negative number (-1) in this fiddle:
http://jsfiddle.net/greenhulk01/kg5ton1t/
function isEven(n) {
if (n == 0) {
return true;
} else if (n == 1) {
return false;
} else if (n < 0) {
return isEven(-n);
} else {
return isEven(n - 2);
}
};
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false
I understand everything that is going on in this recursion except for how "return isEven(-n);" is being handled. Using console.log i can see it is returned as undefined so not sure why it is caught by the false statement.
Any pointers to help my understanding would be really appreciated.
Cheers.
isEven(-n) just takes advantage of the fact that if -n is even, n is even, too. So basically isEven(-10) calls isEven(10)
BTW: Did you try isEven(1.5)? I'd expect false, but I'd guess you'd get a stack overflow. I'd write this as
function isEven(n) {
if (n < 0) {
return isEven(-n);
}
if (n >= 2) {
return isEven(n - 2);
}
return n == 0;
};
BTW 2: Without using recursion, you could just write
function isEven(n) {
return n % 2 == 0;
}

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