Check if number is not integer in recursion js [duplicate] - javascript

This question already has answers here:
How to check if a variable is an integer in JavaScript?
(41 answers)
Closed 1 year ago.
I have a recursion function which calculates factorial for a given number.
function findFactorial(num) {
if (num < 1 || !num.isInteger) {
return "error";
} else {
return num * findFactorial(num - 1);
}
}
console.log(findFactorial(7));
I want to check if number is less then 1 OR is not integer - and return "error" for it.
Code I tried above isn't working and giving me "error" every time function is called.

You have three issues in your code.
First your code will always return "error", since you will always come to the point where num == 0.
Second you have no termination condition (except for the wrong return "error"), so the recursion will never return a valid value.
And last but not least, you try to call a function isInteger() but this function does not exist for the num object.
Here is the valid code:
function findFactorial(num) {
if (isNaN(num) || num < 1) {
return "error";
}
if (num == 1) {
return 1;
}
return num * findFactorial(num - 1);
}
console.log(findFactorial(7));

num.isInteger function is not availble in js. We have Number.isInteger(val).
Some code changes needed.
When a number is not an integer or is a negative number then only we need to return the error.
When a number reaches 1 then we need to return 1 itself to get then factorial values.
See the below code.
function findFactorial(num) {
if (!Number.isInteger(num) || num < 0) {
return "error";
} else if (num <= 1) {
return 1;
}
else {
return num * findFactorial(num - 1);
}
}
console.log(findFactorial(7));
console.log(findFactorial(-5));
console.log(findFactorial("six"));

Related

javascript code, create a function that returns a boolean depending on whether or not a number is even or not?

var i = 1;
var numberCounter = 0
function isEven(num){
if (i % numberCounter === 0) {
console.log('true');
} else { console.log('false');
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
Im not exactly sure where i went wrong here, i am trying to create a function that returns a boolean depending on whether or not a number is even or not.
in order to check if a number is even or not you should check to see if the modulo of 2 with the number is 0. other then that in order to return a value from a function you should use the keyword return. therefor the isEven function should be:
function isEven(num){
return num % 2 === 0;
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
(even number) % 2 = 0 and with ! you will the 0 as 1 in boolean.
% => module
/ => division
const isEven = number => !(number % 2)
isEven(2) // true
const isOdd = number => !!(number % 2)
isEven(3) // true
In your code :
var i = 1;
var numberCounter = 0
function isEven(num){
if (i % numberCounter === 0) {
console.log('true');
} else { console.log('false');
}
Note that i is equal to 0 and numberCounter is equal to 0. No matter which number is passed in your function, its value won't be considered.
You want to define if a number is odd or even. As a matter of fact the number you want to estimate is the parameter of the function.
A basic definition would be that an odd number can be divided by 2. It means that the remainder of the division is equal to 0.
the if statement concerns the num (passed as parameter) and the remainder.
I took your code and modified it. Saar Davidson answer is much more better and effective (in a single line).
function isEven(num){
if (num % 2 === 0) {
console.log('true');
return true;
} else {
console.log('false');
return false;
}
}

Javascript function that finds the next largest palindrome number

I want to write a function that finds the next largest palindrome for a given positive integer. For example:
Input: 2
Output: 3 (every single digit integer is a palindrome)
Input: 180
Output: 181
Input: 17
Output: 22
My try
function nextPalindrome(num) {
let input = num;
let numToStringArray = input.toString().split('');
let reversedArray = numToStringArray.reverse();
if (numToStringArray.length < 2) {
return Number(numToStringArray) + 1;
} else {
while (numToStringArray !== reversedArray) {
// numToStringArray = num.toString().split('');
// reversedArray = numToStringArray.reverse();
num += 1;
}
return numToStringArray.join('');
}
}
As a beginner, I thought that the numToStringArray would constantly increment by 1 and check for whether the while-statement is true.
Unfortunately it doesn't. I commented out two lines in the while-statement because they seemed somewhat redundant to me. Thanks to everyone reading or even helping me out!
The reason your code doesn't work is because you don't have any code updating the conditions of your while loop. So if you enter it once, it will loop indefinitely. You need to do something inside of the while loop that might make the condition false the next time through the loop, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else {
while(num !== getReverse(num)) {
num += 1;
}
return num;
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));
You could also solve this pretty cleanly using recursion, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else if(num === getReverse(num)) {
return num;
}
else {
// if not the same, recurse with n + 1
return nextPalindrome(num + 1)
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));

Writing a function that determines if both integers a user enters are odd numbers

How would you write a function that determines if the two numbers a user enters is both odd and returns a boolean value that is true if both numbers are odd? I already know how to write a function that determines if the two numbers a user enters is even or not.
Try:
function bothOdd(num1, num2) {
if (num1 % 2 == 1 && num2 % 2 == 1) {
return true;
}
return false;
}
window.alert(bothOdd(1, 2));
window.alert(bothOdd(1, 1));
That pretty easy and simple
numbersOdd(1,2); // return false
numbersOdd(14, 222); // return true;
function numbersOdd(n1, n2) {
return n1%2 === 1 && n2%2 === 1;
}

What is wrong with my javascript recursion?

What is wrong with this recursion function?
fac(5) gives NaN
function fac(num){
while(num>2){
return(num*fac(num-1))
}
}
fac(1) returns nothing, which is undefined, and undefined*1 is NaN, that's why.
Change your code to
function fac(num){
return num>2 ? num*fac(num-1) : 1;
}
The correct way should be:
function fact(num) {
if(num > 2)
return num * fact(num - 1);
else
return num;
}
NaN - not a number error , occurs usually but not limited to when we try to apply a numerical operation to a value which is not a number.
The Issue at hand is when the input value is less than 2 , the function return undefined, which is not a number, so the return (num*fac(num-1)) will fail due to num * undefined.
to fix this , we have to return a value when number is 2 or less than 2.
function fact(num) {
if(num > 2)
return num * fact(num - 1);
else
return num;
}
What's wrong with your code
function fac(num){
while(num>2){
return(num*fac(num-1))
}
}
No return value for num <= 2. So, at some point your code will multiply Number with undefined which results in NaN
while loop is not needed
function fac(num) {
return (num > 2) ? num * fac(num - 1) : 1;
}
alert(fac(5));

How to determine if a number is odd or even in Java script [duplicate]

This question already has answers here:
Testing whether a value is odd or even
(23 answers)
Closed 9 years ago.
Can anyone point me to some code to determine if a number in JavaScript is even or odd?
I'm trying to do something like:
if(intellect is even)
{
var magic1 = intellect/2;
}
else
{
var magic1 = (intellect-1)/2
}
var magicdamage = Math.floor(Math.random) * (intellect + weaponi) + magic1
Use the modulus operator
if(intellect % 2 == 0)
{
alert ('is even');
}
else
{
alert('is odd');
}
I think the most robust isEven function is:
function isEven(n) {
return n == parseFloat(n) && !(n % 2);
}
which leads to:
function isOdd(n) {
return n == parseFloat(n) && !!(n % 2);
}
See Testing whether a value is odd or even
if( var % 2 == 0){ /*even*/} else {/*odd*/}
Works for Java, Javascript and any other language. It's a very simple solution, that's why it often doesn't come into your mind until you've seen it somewhere.
The modulo operator % will return the remainder of a division. If the number being divided is even, the remainder is 0.
Like this:
var i = 2;
if (i%2)
// i is odd
else
// i is even
Try using this:
var number = 3;
if (number % 2)
{
//it is odd
}
else
{
//it is even
}

Categories

Resources