how does Increment and Decrement work in Javascript - javascript

Can someone please explain why this function returns 0?
Shouldn't it return 1 since n++ = n and --n = n-1?
var x = function(n) {
return n++ - --n;
};

n++ is a post-increment, so first return the value, then will add 1 to it:
var n = 1;
console.log(n++); //shows 1, increments `n` to 2
console.log(n);//shows 2
console.log(n++); //shows 2, increments `n` to 3
--n is a pre-decrement - the value is first reduced by 1 and then return
var n = 3;
console.log(--n); //shows 2, `n` is already set to 2
console.log(n);//shows 2
console.log(--n); //shows 1, `n` is already set to 1
Here is an example to explain how this is being evaluated: When it's being evaluated:
var x = function (n) {
return n++ - --n;
};
x(5);
0. First n = 5 we go from there:
n = 5
n++ - --n
1. The post-increment has the highest precedence here, so we start with that.
2.n++ will return 5 but also change n to 6. So if we resolve that we have:
n = 6
5 - --n
3. Next in the order of precedence is the the pre-decrement operation.
4. --n will reduce n and return the new value, so:
n = 5
5 - 5
5. Finally, we solve the subtraction and get 0.

n++ - --n
if n = 10, then the value of (n++) is 10, but after that n is increased by one.
So n = 11 after evaluating (n++). if n = 11, (--n) = 10.
n++ - --n
--- ----- ---
10 n = 11 10
so the result is 0

This is a left to right evaluation and the incrementation is done after its value is used.
So lets assume the input is 10
Evaluate to 10 then increase then decrease so 10 - 10 the final expression.

Let's say n = 10
1. n++ will return the original value that n held before being incremented. And before going to the next operation n will be 11.
2. --n will decrease increased value(11) by 1, and then return the decreased value.
3. Finally, 10 - 10 is 0
Arithmetic Operations

Related

Decompose a number in prime numbers

How can I find a number within the interval (from 1 to given number) which is when decomposed into prime numbers has the maximum amount of them.
Example:
Input: 9
Output: 8
Explanation:
8 = 2 * 2 * 2 (3 primes)
7 = 7 * 1 (1 prime)
6 = 3 * 2 ( 2 primes)
And so on... At the end, we'll see that 8 has the greatest amount of primes in decomposition.
Specification:
If there're several numbers having the same amount of primes in decomposition, return the greatest of them.
Okay, I think I understood your requirement.
Here's a simple script to do what you have asked.
//source of this function: https://jsfiddle.net/JamesOR/RC7SY/
function getAllFactorsFor(remainder) {
var factors = [], i;
for (i = 2; i <= remainder; i++) {
while ((remainder % i) === 0) {
factors.push(i);
remainder /= i;
}
}
return factors;
}
function calculate(x) {
lastFactorCount = 0;
highestNumber = 0;
while (x) {
currentCount = getAllFactorsFor(x).length;
if (currentCount > lastFactorCount) {
lastFactorCount = currentCount;
highestNumber = x;
}
x--;
}
return highestNumber;
}
console.log(calculate(7)); //output: 6
console.log(calculate(11)) //output: 8
This pass the two test cases you have given. I borrowed the getAllFactorsFor() function from a jsfiddle I found since we don't need to reinvent anything ;)
calculate() function takes in an input number, then it loops through every number from x to 0, counting how many factors it has, and it keeps track of the last factor count while decrementing x in each iteration.
Finally it outputs the number with highest factor count. Simple.
Hope it helps!!
Notice that after 2 and 3, the next prime is 5, which is bigger than 2*2 (obviously). Therefore, using 2*2 will ALWAYS be better for amount of prime factors, than any higher prime. The number with the highest amount of 2 as prime factors which is still lower or equal is 2 ** Math.floor(Math.log2(num)). The only thing we need to check is whether replacing the last prime factor 2 with a 3 will still be below the number, as that may happen, and would yield a bigger number. Note again, using more than one 3 would be 3*3 = 9 > 8 = 2*2*2, which cannot be a solution again. All of that together yields that the solution should simply be
const f = num => {
let twoEnd = 2 ** Math.floor(Math.log2(num));
let threeEnd = twoEnd / 2 * 3;
return threeEnd <= num ? threeEnd : twoEnd;
}
Some handling for numbers smaller than 2 may be necessary, depending on the circumstances.

Not able to understand javascript behaviour

I am trying to execute the following code
var n = 100;
var sum =0;
while(n>0)
{
sum = sum + n%10;
n = n/10;
}
console.log(sum);
The result should be 1 but javascript is returning
1.1111111111111112
Also, when I ran individual statements it is giving perfectly fine result,
what could be the possible reason?
The result it is giving is correct -
Lets go into while loop
For first iteration n=100 so n%10 = 0 and sum = 0, after first loop sum = 0 and n = 10
In second iteration n%10 = 0 and sum = 0,
after second iteration sum = 0 and n = 1
For third iteration n%10 = 1 and sum =0,
after third iteration sum = 1 and n = 0.1
For fourth iteration n%10 = 0.1 and sum = 1,
after fourth iteration sum = 1.1 and n = 0.01
and so on so forth
finally the answer would be 1.1111111111....... tending to infinity so it becomes 1.1111111111111112
Hope this helps
EDIT
If you want final answer as 1, intialise n as 0.9(n = 0.9)
No, the result won't be 1. Notice that your loop is dividing n by 10 every iteration, and that the continuing condition is n > 0, which will take many iterations till it happens:
n=100, n%10=0
n=10, n%10=0
n=1, n%10=1
n=0.1, n%10=0.1
n=0.01, n%10=0.01
...
So, the result is correct: 1.1111111... The 2 at the end is no more than a rounding decimal error (minimal).

Sorting out numbers in for loops

So I am determining which is a prime number and which isn't, but I am just not understanding how it ends up with the correct output.
So the first starts at 2 and loops by 1 to 100. Easy.
But the second starts at 0, and loops by y + itself, this would make sense, but in determining the primes, it should mess up, atleast I thought
it's like: 1+3 = 4 or 2 + 4 = 6 or 3 + 5 = 8
and that works, but what happens to let's say the 15? that isn't a prime number.
How is numbers like that sorted in the loop?
var prim = [];
var notprim = [];
for(var x = 2; x <= 100; x++){
if(!notprim[x]){
prim.push(x);
for(var y = 0; y <= 100; y = y+x){
notprim[y] = true;
document.write(y);
}
}
}
You have an Array notprim that you can imagine as [undefined × 100], and !!undefined === false, i.e. undefined is falsy
If for some number n you have notprim[n] falsy, you assume it means n must be a prime number and add it to another Array, prim
Then you set all multiples of n to be truthy in notprim, i.e. if n is 3, you set notprim[n * x] = true;, i.e. 0, 3, 6, 9, 12, 15, etc
You then look for the next falsy index in notprim to start again
The reason the first loop starts at 2 is because 2 is the first prime number, starting from 1 or 0 would cause the assumption that "notprim[n] falsy means n is a prime number" to fail
Great, but what about the other loop? Well, one way of going through n * x is to add n to itself x times. When you're thinking of it this way, you can then limit how high you go without knowing a maximum multiplier in advance by looking at the running total, for example in a for loop
for (t = 0; t <= 100; t = t + n)
// t ∈ nℤ, 0 <= t <= 100
but what happens to lets say the 15?
When you've found the prime number 3, you then flag all multiples of 3 to be excluded from your search for primes. 15 is a multiple of 3 so gets flagged as not a prime. Hence your if (!notprim[x]) does not pass
You can reduce the number of iterations this code needs by excluding 0 and x from the second for loop; i.e. begin from the index y = 2 * x

power function. Why set result = 1 at start of loop?

I have no problem with the code I am posting below as it works fine but I was just hoping someone could explain to me why var result = 1.
The way I understand it now is that "result *= base" is the same as "result = result * base." With this being the case wouldn't the power also just be the number inputed into exponent paramenter? 1 * 10 = 10 etc... Thanks in advance!
var power = function(base, exponent) {
var result = 1; // <--- Why this???
for (var count = 0; count < exponent; count++)
result *= base;
return result;
};
console.log(power(2, 10));
Because result needs to be a number with a value before you can multiple it by another number. NaN * base === NaN and 0 * base === 0
Try removing it and see what happens:
var power = function(base, exponent) {
var result;
for (var count = 0; count < exponent; count++)
result *= base;
return result;
};
console.log(power(2, 10)); // output: NaN
The way I understand it now is that "result *= base" is the same as "result = result * base." With this being the case wouldn't the power also just be the number inputed into exponent paramenter? 1 * 10 = 10 etc...
Your result *= base is in a loop. So each time you go through the loop you are updating the result variable with a new value. So first time through the loop you have:
result = 1 * 10
And the next time you have:
result = 10 * 10
And the next:
result = 100 * 10
And so on...
If you moved the var result = 1 part inside the loop, then your function would be broken as result would get reset on each iteration.
result is initialized to base to the power zero, which happens to be 1.
Then you multiply it exponent times by base, resulting in base^exponent.
so 2^10 = 1 * 2 * 2 * 2 * 2 .. 10 times.
You have two ways of solving the problem,
Either you start from 1 and multiply the base with itself n times (like in your example), or you start from base and you multiply n-1 times:
var result = base;
for (var count = 0; count < exponent - 1; count++)
result *= base;
//this will return wrong result if you call power(2, 0)
The first case is obviously better since the base can be 0.
The shortest answer to the question is because base ^ 0 = 1

Random number in ternary statement

I borrowed this script (which had 3 pages) and added another 2 pages. The problem is that it only randomizes between the first 3 on the list. I don't quite undertand the ternary if/else either. If n is greater than 3, it's 0. Else if n is greater than 8, it's 1. Else 2? Did I get that right? It seems like a weird way to do it. How would I get it to randomize between 1 and 5?
<script type="text/javascript">
(function(n){
var pages = ['Happy.html', 'Sad.html', 'Pensive.html', 'Eager.html', 'Inquisitive.html'];
n = n < 3? 0 : n < 8? 1 : 2;
window.location.replace(pages[n]);
})(Math.floor(Math.random() * 10));
</script>
you dont need the ternary operator.. you can just do this
function(n){
//everything except the ternary operator
}(Math.floor(Math.random()*10)%5)
The output of this expression is randomly between 0 and 4. not 1 and 5. this is required because the index of the array of 5 elements is between 0 and 4 inclusive.
Do this:
<script type="text/javascript">
(function(n){
var pages = ['Happy.html', 'Sad.html', 'Pensive.html', 'Eager.html', 'Inquisitive.html'];
window.location.replace(pages[n]);
})(Math.floor(Math.random() * 5)); // Gets a random number between 0 and 4
</script>
or call this function borrowed from here:
<script type="text/javascript">
function randomFromInterval(from, to)
{
return Math.floor(Math.random() * (to - from + 1) + from);
}
(function(n){
var pages = ['Happy.html', 'Sad.html', 'Pensive.html', 'Eager.html', 'Inquisitive.html'];
window.location.replace(pages[n - 1]);
})(randomFromInterval(1, 5)); // Gets a random number between 1 and 5
</script>
In order to completely understand the ternary statement you presented, you need to know about Operator Precendence in JavaScript.
Take a look at this document: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
You got it right about how the ternary statement is going to be executed.
n = n < 3? 0 : n < 8? 1 : 2;
can be translated into
if (n < 3) {
n = 0;
}
else if (n < 8) {
n = 1;
}
else {
n = 2;
}
So it is more clear to understand what is going on.
And, here is how you get random int.
function randInt(n, min) {
return (Math.floor(Math.random() * n)) + (min || 0);
}
var r = randInt(5, 1); // get random number from 1 to 5

Categories

Resources