Check if number is divisible by another number in JS - javascript

I am pretty new at this stuff, and I am solving a series of questions, but I've got lost in this one.
I have to verify if a number can be divided by other, and the answer must be true or false.
I got his
function solucao(numero, x) {
solucao(numero % x);
if (solucao === 0) {
resultado = true;
}else{
resultado = false;
}
}
But I'm getting runtime error and can't see whats is missing.

So you want to check if a number numero is divisible by x. The modulo operator can help. Try this:
function solucao(numero, x){
if (numero % x == 0){
return true
}
else {
return false
}
}

function solucao(numero, x) {
let resultado;
if (numero % x === 0) {
resultado = true;
}else{
resultado = false;
}
return resultado;
}
I think you get confused at some point. You are calling the function, inside of itself. You should do like this, and also, declare the result variable.

I am sure this will help:
function checkIfDivided(){
// in this section the variables come from an html document
var number=parseInt(document.getElementById("number").value);
var divisor=parseInt(document.getElementById("divisor").value);
if(number%divisor==0)
return true;
else return false;
}
or
function checkIfDivided(number,divisor){
//in the function the variable are given as parameters
if(number%divisor==0)
return true;
else return false;
}

Looks like two things to me:
You haven't declared your 'resultado' variable ( this can be as simple as just typing 'let resultado;' without the single quotes
You haven't returned your 'resultado' variable after the if/else statement
Right now, your function is using an undeclared variable and not returning anything, so that is why you are getting an error. Fix the two above steps and you should be good! :)

You clearly understand that the modulus operator is the way to go. Using it we discover that 12 is divisible by 3 because 12 % 3 return zero. Zero is considered a "falsy" value while any other number is considered "truthy".
Given this then if 12 % 3 returns a "falsey" value (zero) we can't use the result directly. But what if we can "flip" false to true? We can, using the not operator (!).
Using the ! operator on the result of a math problem requires the use of parentheses around the math problem itself.
So the problem in code becomes (12 % 3) and to 'flip' it with the ! operator it becomes
!(12 % 3).
This is proven below with:
console.log(!(12 % 3)) --> logs true
console.log(!(12 % 5)) --> logs false
The function implementation of that is simple and also proven:
console.log(isDivisible(12,3)); --> logs true
console.log(isDivisible(12,5)); --> logs false
console.log(!(12 % 3))
console.log(!(12 % 5))
function isDivisible(number, x){
return !(number % x);
}
console.log(isDivisible(12,3));
console.log(isDivisible(12,5));

There is one other way to do so and i think its much cleaner.
console.log(Number.isInteger(10/2)) //true
console.log(Number.isInteger(4/2)) // false
//a must be greater than b
function check(a,b) {
console.log(Number.isInteger(a/b))
return Number.isInteger(a/b)
}
check(10,5)//true
check(8,3)//false

Related

Javascript: Function returning last element of array

I'm taking Colt Steele's Udemy Course titled: "The Web Developer Bootcamp 2020". I have however become stuck on a certain coding exercise. The exercise objective is as follows: Please write a function called lastElement which accepts a single array argument. The function should return the last element of the array(without removing the element). If the array is empty, the function should return null.
I have tried coming up with a solution but cant seem to figure it out. My current best guess is this :
function lastElement (num) {
if (num !== undefined){
return num[num.length -1];
} return null;
}
I'm interested in knowing why the function I have written doesn't work and some pointers on how I should rethink the function, so that it does work.
Best Regards Andreas
Change to this condition.
if (num && num.length>0)
You can use this:
function lastElement(arr) {
if(arr.length>0){
return arr[arr.length-1];
} else{
return null;
}
change your condition to:
if(num && num.length>0)
additionally, if they decide to enter an argument that is not an array,
if(num && Array.isArray(num) && num.length>0)
The problem lies in the difference of truthy and falsy values:
Empty array is truthy but undefined is falsy, so []!==undefined is true, but:
num[num.length -1];
means:
num[-1];
which is undefined .
function lastElement(test) {
if (test.length == 0)
return null;
else
return test[test.length - 1];
}

Possibility to declare variable from function in IF statement?

I'm back again. I had this little question about a possibility that I could declare a variable in the IF condition from a function, and to use it inside the statement itself.
Ok so, I'm curious to see if there's a way to declare a variable inside an IF statement's condition, and use that further along the statement as follows:
function SomeFunc() {return true}
if (let n = SomeFunc()) {
console.log(n); // true
// n is truthy
} else {
// Would never run, because it always returns true.
// This is just an example though, where it can return a truthy or falsy value dependent on the input context I could give it.
console.log(n); // false (if it actually returned 'false')
// n is falsy
}
Is there any way to do this, without having to run the function twice and not have it run outside the IF statement?
(Not like this though):
let n = SomeFunc();
if (n) { ... } else { ... }
// Or this:
if (SomeFunc()) {
let n = SomeFunc();
} else { ... }
I'd like to have one function being declared inside the condition, to minimalise line usage and have it - for me - clean. I hope there's a way to declare a variable inside of an IF condition.
Thank you in advance.
~Q
The syntax does not allow let, const or var to appear at that position.
But you could just define the variable (without initialisation) and then do the if:
let n;
if (n = SomeFunc()) {
// n is truthy
} else {
// n is falsy
}
If you want to limit the scope of that variable just to that if, then put it inside a block:
// other code...
{
let n;
if (n = SomeFunc()) {
// n is truthy
} else {
// n is falsy
}
}
// other code...
Of course, if your function has no other code, then no extra block is needed: the function's block will apply.
Many will disagree with you that an assignment within an if condition is clean. Best practice is to avoid such side effects in a condition, although opinions differ on this. Still, it does not take more characters to write it as follows, and it looks cleaner to me:
{
let n = SomeFunc();
if (n) {
// n is truthy
} else {
// n is falsy
}
}
As function expression
One other approach is to use an immediately invoked function expression, to which you provide the function's return value as argument:
(n => {
if (n) {
// n is truthy
} else {
// n is falsy
}
})(SomeFunc());
Ternary Operator
For a terse syntax use ternary operator:
var/const/let variable = (condition) ? value if true : value if false
The parenthesis wrapped around the condition are optional.
Demo
/*
Condition: if (number is greater than 10) ?
return true
: else return false
*/
const gTTen = number => { return (number > 10) ? true : false; }
console.log(gTTen(11));
console.log(gTTen(9));
function ternary(number) {
/*
Using the previous function then store its return in a
variable
*/
const tenFilter = gTTen(number);
/*
Condition: if (previous value is true AND the number is
less than 20) ?
range is 30
: else range is 0
*/
let range = (tenFilter && number < 20) ? 30 : 0;
/*
Condition: if (range = 30) ?
result is (the first string)
: else result is (the last string)
*/
let result = range === 30 ? `${number} is within range` : `${number} is not within range`;
return result;
}
console.log(ternary(50));
console.log(ternary(15));
Ah! I figured this out a few days ago, but didn't have time to respond. I could use local variables that I only overwrite while performing the statements.
Here's an example.
function retClone(bool) {
return bool; // Returns same input context for example.
}
if (t = retClone(true)) {
console.log(t); // true
// t is truthy, because we get `true` returned.
}
if (t = retClone(false)) {
// Wouldn't run.
// t is falsy.
} else {
console.log(t); // false
}
Thank you all who responded. ~Q

What is the flaw in my thinking in this javascript boolean function?

So I am suppose to create a function that reverses a values boolean parameter. [Here][1] is what I came up with:
I really just want to understand what is my flaw in thinking. How can I fix my approach?
Please have a look to your code:
function not(x) {
if (1 == true) {
return "true";
} else if (0 == false) {
return "false";
}
}
Whats right:
function not(x) {
}
Whats goes wrong:
if (1 == true) {
// ^ ^^ ^^^^
// | | boolean
// | equal (not type safe)
// number
You compare constant values. In this case a number 1 with a boolean true. The comparison operator is equality == and this "converts the operands if they are not of the same type". That means that one is equal true and the next part is evaluated and
return "true";
ever, because there are no variables involved. The rest of the else part is never reached, as well as the next comparison, which is never reached.
As well as 'true' is always returned, it is not the type you want, because you need a boolean and return a string.
What should change:
if (x == true) {
// ^
// the parameter of the function
return true;
// ^
// boolean
} else {
// ^
// no other if
return false;
// ^
// boolean
}
or a short version of all with the logical NOT operator !:
function not(x) {
return !x;
}
I assume you want to write the function for learning purpose, because you do not need to write it in practice. Javascript already has ! (not) operator.
For your function and implementation would be:
function not(x) {
if(x === true) return false;
else return true;
}
But as I said you can just use ! operator.

Eloquent JavaScript 2nd Edition recursion exercise solution

I attempted to solve the recursion exercise of the online book eloquentjavascript 2nd edition:
Here is what the question states:
We’ve seen that % (the remainder operator) can be used to test whether
a number is even or odd by using % 2 to check if it’s divisible by
two. Here’s another way to define whether a (positive, whole) number
is even or odd:
Zero is even.
One is odd.
For any other number N, its evenness is the same as N - 2.
Define a recursive function isEven corresponding to this description.
The function should accept a number parameter and return a boolean.
Test it out on 50 and 75. See how it behaves on -1. Why? Can you think
of a way to fix this?
Here is what I have attempted and it works:
function isEven(number) {
if (number == 0) {
return true;
} else {
return (-number % 2 == 0) ? true : false;
}
return isEven(number - 2);
}
console.log(isEven(-1));
But, it seems to be a wrong answer because as I understood the author wants me to use - 2 method. I am wondering if this is indeed the correct answer or if it is wrong could someone point me in the right direction.
I think the reason you are getting confused is because you're not understanding how recursion works. The reason it is n-2 is, it is taking the number and subtracting 2 until it is either a zero or one. Therefore giving us a true or false.
Hope that helps. Read over how the process of recursion works.
The alternative solution that doesn't use the modulos operator % or any other built in functions in JavaScript is provided below. This solution instead relies on using another recursion to change negative value of the number.
function isEven(number) {
if (number < 0) {
return isEven(-number);
} else if (number == 1) {
return false;
} else if (number == 0) {
return true;
} else {
return isEven(number - 2);
}
}
console.log(isEven(50)); // true
console.log(isEven(75)); // false
console.log(isEven(-1)); // false
We call isEven(number -2) to go back to the top of the function with the number that was inputed intially but 2 less than before and it will keep doing that until the number is 1 or 0 and then it will be able to return the boolean true or false (even or odd).
I think the problem is to create an isEven function without using a mod/%/remainder operation
function isEven(number) {
if (number < 0) {
number = Math.abs(number);
}
if (number===0) {
return true;
}
if (number===1) {
return false;
}
else {
number = number - 2;
return isEven(number);
}
}
I guess it is important to add to this
it doesn't handle strings
it doesn't handle floats
don't put this into a production application
function isEven(n) {
n = Math.abs(n);
if (n==0)
return true;
else if (n==1)
return false;
else
return isEven(n-2);
}
console.log(isEven(-50)); // → true
console.log(isEven(75)); // → false
console.log(isEven(-75)); // → false
console.log(isEven(-1)); // → false
var isEven = function(n) {
// Get the absolute value of the number
// so we don't have to bother with negatives
n = Math.abs(n);
// We know that if we subtract 2 from our number
// until it is equal to zero, our number was even
// If our number isn't zero, this statement will be skipped
if(n === 0) return true;
// We know that if we subtract 2 from our number
// and it reaches a value of 1, it isn't even
// If our number isn't 1, this statement will be skipped
if(n === 1) return false;
// We subtract 2 from our original number and pass it
// back in to this function to check it over and over again
// until one of the conditions is met and the function can
// return a result
return isEven(n - 2);
}
// We test our function here
console.log(isEven(-21));
This is the leanest method I could come up with. Notice we call our isEven function from within itself and pass in the value of n - 2. This will constantly subtract 2 from our number and check to see if it is equal to 0 or 1 until we get a proper result and return the corresponding boolean.
I hope this clears things up a little.
How about the below code? Seems to work for me.
/*if > 1 keep looking, otherwise return reverse boolean value.
If negative value, inverse, to answer the last part of the question...
Also needed to use parseInt as the text value I used,
was considered a string value!
This being a recursive function which really isn't necessary,
means that in javascript we will get a
stack size exceeded error when the number becomes too large.*/
function isEven(x) {
return (x>1)?isEven(x-2):(x>=0)?!x:isEven(-x);
}
The book wants the following console.log outputs for such values
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-2));
// → ??
The hint says "When given a negative number, the function will recurse again and again, passing itself an ever more negative number, thus getting further and further away from returning a result. It will eventually run out of stack space and abort." So I'm not sure if what I got represents that but my code and console.log outputs is shown below:
let isEven = function(num) {
if (num ===0) {
return true
} else if (num===1){
return false
} else {
return isEven(num-2)
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-2));
// → RangeError: Maximum call stack size exceeded (line 3 in function isEven)```
The question requires that you don't' not to use the modulus operator (%).
// Your code here.
var isEven = function(a){
if (a == 0){ //case 1 : zero is even
return true;
}
else if(a == 1){ //case 2: one is odd
return false;
}
else {
return isEven(Math.abs(a-2)); //solves case 3 (negative numbers)
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ?? ....false
This is the "correct" answer from the website. I say "correct" in quotes because I don't understand the 2nd 'else if' statement's return isEven(-n). Why did the author include the option to turn n into a positive number?
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);
}
Anyways, thought I'd share since I didn't see anybody post THIS answer.
//define recursive function isEven takes a positive whole number
//returns true if even
function isEven(x) {
//define innner function to loop over value
function find(current) {
//check if value == 0, return true
if (current == 0) {
return true
//check if value == 1 return false
} else if (current == 1) {
return false
//loop over value, subtracting 2 each time until either 0 or 1
//which returns the approriate true/false value based on evenness
} else {
console.log(current)
return find(current -2)
}
}
return find(x)
}
If the number is 1 or -1 so ODD, the function returns false,
If the number is 0 so EVEN, it returns true,
If then number nor 1,-1 nor 0 we have to first check if the number is positive or negative,
If the number is negative and less than -1 we call the function again but increase the number by 2 until we get -1 or 0;
If the number is positive and greater than 1 we call the function again but decrease the number by 2 until we get 1 or 0;
So for example, the number is 5 ->it`s positive and greater than 1 so call the function over and over again and decrease the number by 2 until the result will be 0 or 1:
5->3->1 //->false
function isEven(num) {
if (num == 1 || num == -1) {
return false;
} else if (num == 0) {
return true;
} else {
if (num < -1) {
return isEven(num + 2);
} else {
return isEven(num - 2);
}
}
}
Test result:
console.log(`-35 is even: ${isEven(-35)}`); //-> false
console.log(`-1 is even: ${isEven(-1)}`); //-> false
console.log(`0 is even: ${isEven(0)}`); //-> true
console.log(`32 is even: ${isEven(32)}`); //-> true
I see quite a few examples above using math functions and modulo operator. But I guess the author expects a simple recursive function to make the reader understand the functioning of the same and how if not properly defined it can lead to repetitive function calls and eventually lead to overflow of stack. I believe this code below can help you understand:
function isEven(n){
if(n==0){
return true;
} else if(n==1){
return false;
} else {
return isEven(n-2);
}
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
function isEven(num){
if(num %2 == 0) {
return true;
} else {
return false;
}
}
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
function isEven(number) {
while(number>= -1)
{
return isEven(number-2) == 0 && number>-1 ? true : false;
}
}
console.log(isEven(-1));
I hope this helps:
const evenOrOdd = (N) => {
if (Math.abs(N) === 0) {
return console.log('Even');
} else if (Math.abs(N) === 1) {
return console.log('Odd');
}
evenOrOdd(Math.abs(N) - 2);
};
Google Chrome Console code results:
It utilizes all three given arguments on the problem. It can handle negative integers. It does not use the modulo operator. Lastly, I wasn't able to see any code snippet similar to what I provided thus I am enticed to share what I can.

Bitwise AND operations in Javascript

I make a project that reads value from a remote JSON. In this project the remote JSON can give me with one variable 16 different types of alarm. The implementation is by a bynary 16bit value expressed in int. So if there is the third alarm it should return me 8 (bynary 1000) and if the second,eigth and tenth alarm is up it return me 1284 (binary 10100000100). Well when there is no alarm it returns me 0.
So, I create a function in JS (accordly to here) that passing the value returned (8/1284/0 in the example) returns me a simple true or false if there is an alarm. The function is pretty simple:
function IsOnAlarm(passedVal) {
if (passedVal & 0) {
return false;
} else {
return true;
}
}
but it does not function :-(
I create a JSFiddle that shows the problem. How can I solve it? Thanks in advance.
Well as far as I understand you just need to check whether the value is 0. There's no need for any bitwise operation.
function IsOnAlarm(passedVal) {
return passedVal != 0;
}
Side note: passedVal & 0 is always 0 no matter what passedVal is (that's why it always goes to else).
You can do it like
function IsOnAlarm(passedVal) {
if (passedVal != 0) {
return false;
} else {
return true;
}
}
Check this http://jsfiddle.net/KQH43/3/
The AND operator always return false if one of the operands is zero, see below:
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
The easiest way to rewrite your function is as follows:
function IsOnAlarm(passedVal) {
return !!passedVal;
}
Explanation: the double negation operation (!!) allows you to cast the input to boolean. Any non-zero value will evaluate to true, zero evaluates to false.
Check this jsfiddle, it is using bitwise AND comparison.
I've modified your function to make it easier to understand:
function AreAlarmsOn(alarmsToCheck, alarmState) {
return and(alarmsToCheck, alarmState)!=0;
}
It takes alarmsToCheck and checks its bits against alarmState bits, alarmsToCheck can have bits for several alarms if you need to check multiple alarms.
Is this what you're looking for?
var getFlags = function(val) {
var results = [];
for (var i = 0; i < 16; i++) {
results.push(!!((val >> i) & 1));
}
return results;
};
var flags = getFlags(1284);
flags[2] //=> true
flags[8] //=> true
flags[10] //=> true
// all other values ==> false / undefined

Categories