Im currently in process of learning Javascript. And I have seen the following code, which confuses me.
Description of code:
Starting on line 1, the function isOdd takes a number n and returns a boolean (true or false) stating whether the number is odd or not.
Code
var isOdd = function (n) {
if (n % 2 === 0) {
return false;
} else {
return true;
}
};
var isEven = function(n) {
if(n % 2 === 0) {
return true;
} else {
return false;
}
};
Where I am confused.
The code:
n % 2 === 0
I have always taken the following to be the description for %:
% Is the modulus operator. It returns the remainder of dividing number1 by number2.
Which would mean that the if statement in the function isOdd returns false is the difference between n and 2 is 0. But its meant to mean if n is divisible by 2 (even) return false.
I just dont see how its doing that.
In my mind, if we take the even number 30. Apply it to n % 2. We get 15, which is remainder of dividing 30 by 2. 15 does not equal 0, but 30 is an even number, and with this code it would be seen as odd.
Can someone explain this?
The line in question:
if (n % 2 === 0) {
return false;
}
Means "if when you divide n by 2 the remainder is zero, then return false (i.e. n is not odd)".
The "remainder" is whatever is left over when you subtract the nearest multiple, so for example "64 % 10" is 4, since the nearest multiple of 10 is 60, leaving 4.
Taking your example and putting it another way, 30/2 is 15, 30%2 is zero (i.e. whatever is left over after 30/2). Here's more info on the remainder after division.
You're confusing Quotient and Remainder.
When you divide 30 by 2, integer quotient is 15, and remainder is 0. You can also calculate remainder by multiplying integer quotient by divisor and subtracting it from dividend. So for this division remainder is 30 (dividend) - 15 (quotient) * 2 (divisor) = 0.
If n can be divided by 2 it means it's even ->
which means it's not odd ->
isOdd is false
Related
It's a function that returns the sum of all of the odd Fibonacci numbers that are less than or equal to the given number.
I am stuck with the last of the tests, all of them work besides this one.
sumFibs(75025) should return 135721, I've been trying many things but none worked.
function sumFibs(num) {
let f1 = 1;
let f2 = 1;
let fiboNums = [];
while (f1 <= num && f2 <= num) {
if (f1 % 2 !== 0) fiboNums.push(f1);
if (f2 % 2 !== 0) fiboNums.push(f2);
f1 += f2;
f2 += f1;
}
return fiboNums.reduce((pV, cV) => pV + cV);
}
console.log(sumFibs(75025));
Instructions: Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.
The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.
For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.
I tried changing the boolean statement of the while loop as well as the if-statements by adding a condition that evaluates to true if f1 or f2 are less than or equal to the given number
The issue is that once f2 is bigger than num, the loop ends even though f1 is not bigger than num, therefore skipping the last relevant number in the series and excluding it from the results. Here's a revised version that fixes the problem:
function sumFibs(num) {
let f1 = 1;
let f2 = 1;
let fiboNums = [];
while (f1 <= num) {
if (f1 % 2 !== 0) fiboNums.push(f1);
if (f2 <= num && f2 % 2 !== 0) fiboNums.push(f2);
f1 += f2;
f2 += f1;
}
return fiboNums.reduce((pV, cV) => pV + cV);
}
console.log(sumFibs(75025));
I want to check whether a number (7) is divisible by another number (5), If the number is divisible by the number then I need to return the same number. If the number is not divisible by another number I need to make it divisible and return the updated value.
var i =7;
if (i % 5 == 0) {
alert("divisible by 5");
} else {
alert("divisible not by 5");
}
Here if the condition satisfy then I need to return the same value. If the condition is not satisfied I need to add the required number and make it next divisible. (Like 7 is not divisible by 5 so I need add 3 to 7 and return the value 10 which is divisible by 5).
Are there any Math functions exists to implement the same?
What you want, it seems like, is this:
function roundTo(n, d) {
return Math.floor((n + d - 1) / d) * d;
}
For n 10 and d 5, you get 10 back. For n 7 and d 5, you also get 10. What the code does is add one less than the divisor to the input number, and then divides by the divisor. It then gets rid of any fractional part (Math.floor()) and multiplies by the divisor again.
You can do that by using a simple while loop:
function doThat(number, divider) {
while(number % divider !== 0) {
number++;
}
return number;
}
doThat(12, 5); // => returns 15
Here's a fiddle: https://jsfiddle.net/rdko8dmb/
You could use this algorithm:
i % n = r, where i = 7, n = 5, and r = 2.
Then, make i = i + (n - r). i.e. i = 7 + (5-2) → 10. Then you can use this for your division.
Try this
function divisible(dividend, divisor){
if (dividend % divisor == 0) {
return dividend;
} else {
var num = dividend + (divisor-(dividend % divisor));
return num;
}
}
var res = divisible(7, 5);
console.log(res);
Here is the fastest and cleanest way to do that:
function shift(number, divider)
{
return number + (divider - (number % divider)) % divider;
}
It takes number and moves it up by the difference from (our unit) divider to the remainder to make it divisible by the divider. The % divider makes sure that if there is no difference number doesn't get pushed up by a full unit of the divider.
I do not know if this will work for all numbers... But you might try this
7 % 5 = 2. If you subtract 2 from 5 you will get 3... This is the number you need to add to 7. 16 % 5 = 1 subtract 1 from 5 = 4 .. 4 + 16 = 20
Another example 16 % 13 = 3 ... 13-3 = 10 16+10 = 26 26/13 = 2
Here's an example of function that finds next higher natural number that is divisble by y
https://www.jschallenger.com/javascript-basics/find-next-higher-number
Option 1
while (x % y !== 0) x++;
return x;
}
Option 2
if(x % y == 0){
return x;
}
else{
for(i = x+1; i > x; i++){
if(i % y == 0){
return i;
}
}
}
Is there a more effective way to return true if n is a power of two or false if not?
function isPowerOfTwo(n) {
return Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
}
You can actually use ECMAScript5 Math.log:
function powerOfTwo(x) {
return (Math.log(x)/Math.log(2)) % 1 === 0;
}
Remember, in math, to get a logarithm with an arbitrary base, you can just divide log10 of the operand (x in this case) by log10 of the base. And then to see if the number is a regular integer (and not a floating point), just check if the remainder is 0 by using the modulus % operator.
In ECMAScript6 you can do something like this:
function powerOfTwo(x) {
return Math.log2(x) % 1 === 0;
}
See the MDN docs for Math.log2.
Source: Bit twiddling Hacks,
function powerOf2(v) {
return v && !(v & (v - 1));
}
You just bitwise AND the previous number with the current number. If the result is falsy, then it is a power of 2.
The explanation is in this answer.
Note:
This will not be 100% true for programming, mathematical, [also read 'interviewing']. Some edge cases not handled by this are decimals (0.1, 0.2, 0.8…) or zero values (0, 0.0, …)
Using bitwise operators, this is by far the best way in terms of efficiency and cleanliness of your code:
function PowerofTwo(n){
return ((x != 0) && !(x & (x - 1)));
}
what it does is checks the bits that make up the number, i.e. 8 looks like this:
1 0 0 0
x-1 or 7 in this case looks like this
0 1 1 1
when the bitwise operator & is used it invokes an && on each bit of the number (thus 1 & 1 = 1, 1 & 0 = 0, 0 & 1 = 0, 0 & 0 = 1):
1 0 0 0
-0 1 1 1
=========
0 0 0 0
since the number turns into an exact 0 (or false when evaluted as a boolean) using the ! flag will return the correct answer
if you were to do this with a number like 7 it would look like this:
0 1 1 1
-0 1 1 0
=========
1 1 1 0
returning a number greater than zero causing the ! flag to take over and give the correct answer.
A number is a power of 2 if and only if log base 2 of that number is whole. The function below computes whether or not that is true:
function powerOfTwo(n){
// Compute log base 2 of n using a quotient of natural logs
var log_n = Math.log(n)/Math.log(2);
// Round off any decimal component
var log_n_floor = Math.floor(log_n);
// The function returns true if and only if log_n is a whole number
return log_n - log_n_floor == 0;
}
Making use of ES6's Math.clz32(n) to count leading zeros of a 32-bit integer from 1 to 2³² - 1:
function isPowerOf2(n) {
return Math.clz32(n) < Math.clz32(n - 1);
}
/**
* #param {number} n
* #return {boolean}
*/
const isPowerOfTwo = function(n) {
if(n == 0) return false;
while(n % 2 == 0){
n = n/2
}
return n === 1
};
function PowerOfTwo(n){
// Exercise for reader: confirm that n is an integer
return (n !== 0) && (n & (n - 1)) === 0;
}
console.log(PowerOfTwo(3))
console.log(PowerOfTwo(4))
This is for a specific online course that requires an answer in a specific way.
Without using libraries and other methods just loops and .push.
you need to create an inner loop using while
it should start with 1
keep multiplying it with 2 until i,j,k or whatever is greater than the current number(array) so it will have to do 2 4 6 8 10 12 14 16 18 until it is greater than the number
then it will go to the outer loop then repeat again until
const numbers = [5, 3, 9, 30];
const smallestPowerOfTwo = arr => {
let results = new Array;
// The 'outer' for loop -
for (let i = 0; i < arr.length; i++) {
number = arr[i];
// The 'inner' while loop
j = 1;
while (j < number) { //starting from 1 then multiplied by 2 then by 2 again untill it is more than the number
j = j * 2;
}
results.push(j);
}
return results
}
console.log(smallestPowerOfTwo(numbers))
I know this is a very basic question but what does the 0 refer to in the code below
var even = arr.filter(function(val) {
return 0 == val % 2;
});
what does the 0 refer to
Here 0 refers to the Number 0.
0 == val % 2
will evaluate to true or false which you are returning.
0 is the tested value of val modulus (%) 2. When there is no "remainder", as with even numbers, it will return the number 0. For odd numbers it will have a remainder of 1 and the function will return false to filter().
The % is the modulus operator, it works like this
The remainder operator (modulus) returns the first operand modulo the
second operand, that is, var1 modulo var2. The modulo function
is the integer remainder of dividing var1 by var2
MDN
In other words, if val can be divided by 2, the modulus operator returns 0 as there is no remainder, that's why it checks for a zero
Turning the yoda condition around, it makes more sense
val % 2 === 0; // can be divided by 2, so it's even, returns boolean
For instance if val was 4, 16, 200 etc, it would be true, as 4 can be evenly divided by 2.
If val was 3, 9, 201 etc. it would be false, as 3 can not be evenly divided by 2.
0 is just a number which is compared to right hand side expression val % 2
statement 0 == val % 2; returns true if val % 2 is 0 (value of val is even), or returns false is val % 2 is 1 (value of val is odd)
Just for information: Modulo operator returns the remainder(a number) when val is divided by any number
What does the % do in JavaScript?
A definition of what it is and what it does would be much appreciated.
It's a modulo operator. See this documentation or the specification for more information on JavaScript arithmetic operators.
% (Modulus)
The modulus operator is used as follows:
var1 % var2
The modulus operator returns the first operand modulo the second
operand, that is, var1 modulo var2, in the preceding statement, where
var1 and var2 are variables. The modulo function is the integer
remainder of dividing var1 by var2. For example, 12 % 5 returns 2. The
result will have the same sign as var1; that is, −1 % 2 returns −1.
ES6 Update:
As explained in other answers, it returns the remainder after dividing the dividend by divisor, however this is no longer modulo operator, this is remainder operator. the difference being that the modulo operator result would take the sign of the divisor, not the dividend.Quoted from MDN
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of ECMAScript, the difference being that the modulo operator result would take the sign of the divisor, not the dividend.
Example:
-10 % 3 // -1
10 % -3 // 1
It returns the remainder of a division operation. 5%2 returns 1
It is a modulo operator.
It calculates the remainder.
If we do 23 % 10,
first, we divide 23 by 10 which equals 2.3
then take .3 * (the divisor) 10
= 3
That would be the modulo operator.
It returns the remainder of a division operation:
var remainder = 3 % 2; // equals 1
In JavaScript, % is a remainder operator (Not a modulo operator).
remainder operator % (uses Math.truc()):
remainder = -5 % 3 = -2
How is it calculated ?
quotient = Math.trunc(dividend / divisor) = Math.trunc(-5 / 3) = -1;
remainder = dividend - divisor * quotient = -5 - (3 * -1) = -2
modulo function (uses Math.floor()):
modulo(-5,3) = 1
How is it calculated ?
quotient = Math.floor(dividend / divisor) = Math.floor(-5 / 3) = -2;
remainder = dividend - divisor * quotient = -5 - (3 * -2) = 1
For positive numbers, both remainder operator and modulo gives the same result.
5 % 3 = 2
modulo(5,3) = 2
In JavaScript, there is no build-in function for doing modulo operation, so you need to write on your own by using Math.floor() as above. Alternatively even you could easily write using the remainder operator as shown below.
function modulo(n, m) {
return ((n % m) + m) % m;
}
Just in case, if someone is looking for a real modulo function (which would always get the sign of the divisor), you can use this:
function Modulo(num, denom)
{
if (num%denom >= 0)
{
return Math.abs(num%denom);
}
else
{
return num%denom + denom;
}
}
The Math.abs is to prevent the case -12%12 → -0, which is considered equal to 0 but displayed as -0.
Modulus (%) operator returns the remainder.
If either value is a string, an attempt is made to convert the string to a number.
alert(5%3) will alert 2
% performs as the modulo operator, return division reminder. Example:
<script>
var x = 5;
var y = 2;
var z = x % y;
alert(z);
</script>
This will alert 1.
This is what I would do to getModulus, given k > 0. I find it more intuitive as Math.floor(num / k ) in js is exactly num // k in python.
function getModulus(num, k) {
return num - Math.floor(num / k ) * k
}