I'm working through eloquent javascript and I don't understand this bit of code
for (var current = 20; current % 7 != 0; current++)
;
console.log(current);
It states that it checks for the first number greater than 20 that is divisible by 7 and console.log() would produce 21.
But I read that as start at 20, check if current divided by 7 has no remainder to see when we break the loop. But straight away 20 mod 7 == 6 meaning it does not equal 0 or (20 % 7 != 0).
So shouldn't the for loop break straight away and console.log(current) produce 20? What am I missing here?
A loop continues as long as the condition is met.
20 % 7 != 0 // 6 != 0 is true, so condition is met and loop continues
21 % 7 != 0 // 0 != 0 is false, so condition fails and loop halts
"... check if current divided by 7 has no remainder"
No, it's "check if current divided by 7 does NOT have no remainder".
I think the negative condition is throwing you. Basically, you need to ask if the condition is a true statement.
So if I'm the condition, and you're the loop, and I say "six does not equal zero", you would say "that's true", so you would agree to let the loop continue.
But then if I say "zero does not equal zero", you would say "that's false", and would halt the loop.
A clearer condition would be "check if current divided by 7 does have a remainder". No double negative, so it could be written as:
for (var current = 20; current % 7; current++) ;
or as:
for (var current = 20; current % 7 > 0; current++) ;
Nothing is wrong here. Simply change the ; line to this line, and you'll get the idea:
for (var current = 20; current % 7 != 0; current++) {
console.log('current value is ' + current ' +
' and the mod result is ' + current % 7);
}
Related
Considering this code:
var x = 3;
var i = 0;
while (i < 3) {
x += 1;
i += 1;
}
println(x);
Why would the output be 6? Can someone break it down for me?
I understand that x will continue adding 1 to it's value, but why does the i<3 limit it to 6?
The answer will be 6 because your initial value of X is 3.
You have only 3 iterations in your while loop.
i = 0 => x +1 = 4
i = 1 => x + 1 = 5
i = 2 => x + 1 = 6
i = 3 => exit loop
I will explain it step by step
while loop will take values, while i is smaller than 3 right.
X starts as 3 and i starts as 0.
While checks if i < 3. (it is 0 for now )
(x+=1 means x = x + 1 (same for i ))
i was 0, so while loop will start working.
x will become 4 and i will become 1.
second run: i is 1 still lower than 3 so while loop will keep working.
x will become 5 and i will become 2
i is still lower than 3 so while loop will keep working
x will become 6 and i will become 3
now i is equal to 3 so no longer lower than 3. While loop will stop working and you will get the outputs.
But if console.log (x) was in the while loop. You will get all the x results.
The output would be:
4
5
6
So, if your question is why am I getting only 6 as an output? It is because your function comes after the while loop.
Before entering into the loop: x=3, i=0 (i is less than 3, so the condition is true)
After the first step: x=4, i=1 (i is less than 3, so the condition is true)
After the second step: x=5, i=2 (i is less than 3, so the condition is true)
After the third step: x=6, i=3 (i is not less than 3, so the condition is false)
Because the condition is false, it is exited from the loop and the value of x is printed in the output.
Also, println() is not defined in JavaScript. We can use console.log().
The code of
var x = 3;
var i = 0;
while (i < 3) {
x += 1;
i += 1;
}
increments x and i repeatedly. Initially, i is 0, which is important, as its incrementation's result determines whether the loop should continue. Since the loop criteria is that i < 3 is (still) true, starting from 0 and adding 1 to the value of i, your loop's block will be executed 3 times (it's executed for i=0, then it's executed for i=1 and then it's executed for i=2 and finally, for i=3 it's not executed, because the condition of i < 3 is no longer true when i=3).
Since the loop block is executed 3 times and both i and x is incremented by 1 at each execution, their value increases by the same value during the process. Since i was increased by 1 a total of three times, its value was changed from 0 to 3 (0 + 1 + 1 + 1 = 3). Since the initial value of x was 3, it changed from 3 to 6 (3 + 1 + 1 + 1 = 6).
So,
I'm starting to learn how to code and now I have only one problem.
My code is functioning very well, until he says that the numbers 1 and 0 are prime.
I already tried to add them to exception, change the calculation and still printing that is prime.
Here's the code:
function testPrimeNumber(num)
{
Number(num)
for (var i = 2; i < num; i++)
{
if (num % i == 0)
{
return ("The number "+num+" isn't prime.");
}
else {}
}
return ("The number "+num+" is prime.");
}
console.log("result for 1:", testPrimeNumber(1));
What am I doing wrong here?
You should test for 0 and 1 at the start of the function. At the moment your code is skipping the for loop (because 1 < 2 and 0 < 2) and going straight to saying the number is prime.
I can understand how this code produces Fizz , Buzz when divisible by 3 , 5. But confused about how it produces FizzBuzz when divisible by both 3 and 5, because i do not see any if condition which satisfies divisible by both 3 and 5. Please explain.
for (let n = 1; n <= 100; n++) {
let output = "";
if (n % 3 == 0) output += "Fizz";
if (n % 5 == 0) output += "Buzz";
console.log(output || n);
}
Both if statement conditions evaluate to true, so it adds both "Fizz" and "Buzz" to "", which results in "FizzBuzz". The += operator is appending text to output.
The use of output += ...; allows for the variable to be populated with FizzBuzz if/when the iteration is divisible by both 3 AND 5.
I'm not sure i understand your issue
You don't understand why you get FizzBuzz sometimes ?
For example when n=15 you get it.
Because 15 % 3 = 0 ( 15 = 3*5 ) and 15 % 5 = 0 (15 = 5*3 )
It is the same for 30, 45, 60, 75, 90.
Since i += i is an abbreviation for i = i + i, the following code
for (var i = 0; i<=10; i++) {
console.log(i += i) }
should output:
1. 0, because 0 += 0 + 0 (i = 0)
2. 2, because 0 += 1 + 1 (i = 2)
3. 6, because 2 += 2 + 2 (i = 6)
4. 12, because 6 += 3 + 3 (i = 12)
However, although the console does output the values of 1. - 3., namely, 0, 2, and 6, correctly, the value that I get for 4., which is 14, is not the value that I predicted (the lines 1. - 4. above were typed out before the for-loop was executed) the for-loop would output (=12).
What am I interpreting wrong here?
The code itself is evidently uninteresting, but nonetheless I am curious why it works the way it does.
So basically, you are adding one then double the number in each iteration, starting with 0.
Then you should get: 0, 2, 6, 14. I think your math, not code, is wrong here.
Recall that for loops have four parts: Initialiation, Test, Body, and Increment.
...and they work like this:
Initialization
Test, jump to after loop if test is false*
Body
Increment
Go to step 2
So, here's the way that loop works:
(Initialization) i = 0
(Test) Since 0 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 0, i = 0 + 0 is i = 0.
Log that
(Increment) Evaluate i++. Since i is 0, it becomes 1
(Test) Since 1 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 1, i = 1 + 1 is i = 2
Log that
(Increment) Evaluate i++. Since i is 2, it becomes 3
(Test) Since 3 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 3, i = 3 + 3 is i = 6
Log that
(Increment) Evaluate i++. Since i is 6, it becomes 7
(Test) Since 7 is <= 10, keep going
(Body):
Evaluate i += i: Since i is currently 7, i = 7 + 7 is i = 14
Log that
(Test) Since 14 is not <= 10, stop
* "Test, jump to after loop if test is false" Technically, not just false, but anything falsey, which is 0, null, undefined, NaN, "", or of course, false.
The problem is that you are updating i inside the loop as well as for the loop itself. This means you need to look at both updates to see what really happens to i. Here are the steps unrolled:
for(var i=0; i<=10; i++){ ...
// i = 0 here
console.log(i += i);
// logged 0 += 0 (0)
// now i will be incremented to 1
console.log(i += i);
// logged 1 += 1 (2)
// increment i to 3
console.log(i += i);
// logged 3 += 3 (6)
// increment i to 7
console.log(i += i);
// logged 7 += 7 (14)
// increment i to 15
// ... etc
It looks like you just missed the fact that += is also updating the i inside the loop, not just from the ++ incrementor.
This is what your code does:
1. i starts with 0, then you assign to it 0 + 0. console logs i as 0
2. i increments to 1, then you assign to it 1 + 1. console logs i as 2
3. i increments to 3, then you assign to it 3 + 3. console logs i as 6
4. i increments to 7, then you assign to it 7 + 7. console logs i as 14
Note that i += i is not the same as i += i + i, but as i = i + i. It is an assignment, and the value returned is the new value of i.
When trying out the code below as a solution for the Euler Project problem 5. The problem is find the smallest number equally divisible by all numbers from 1 to 20. Every time it is run it presents "Unresponsive Script" window and I need to physically stop the script from running. It seems like something is causing it to hang but I can't quite figure out what. The alert window seems to point to an error with the line the while() starts on but I can't see anything wrong with it.If it looks like it should work I'd appreciate anyone trying it on their machine to see if it works. That way I can eliminate it as a local problem. All suggestions welcome.
var divisible = false;
var n = 2520; // first number divisible by all numbers 1-10
while(divisible === false){ // something wrong here??
n += 2520;
for(var i = 11; i < n; i++) {
if(i % n !== 0){
break;
}
if(i === 20) {
divisible === true;
}
}
}
if(divisible === true){
return console.log("Answer: " +i);
}
Because you break out of your for loop if i % n isn't 0 the very first time. And you never set divisible to true - divisible === true isn't the same as divisible = true
There are several errors in the original code, some pointed out in the answer above. To make it work several fixes are needed.
First, the boolean divisible must be correctly set to true using the assignment operator = inside the for loop instead of === which is used only to check if two values are strictly of the same type AND value.
The next problem is the conditional part of the for loop i < n should be i < 20 because the loop is checking if numbers between 11 and 20 divide evenly into n.The last fix to make the code run correctly is the order of the condition if the first if statement which should read if(n % i !== 0) and not if(i % n !== 0). I think it might be this specific part that caused the code to crash and generate the "Unresponsive Script" alert in the browser.
Here is the fixed code.
var divisible = false;
var n = 2520; // smallest number divisible by all numbers 1-10
while(divisible === false){
n += 2520; // increment n on each new pass
// loop numbers between 11 and 20
for(var i = 11; i <= 20; i++) {
if(n % i !== 0){ // check if i divides equally into n
// if not break out of current loop and start again
break;
}
// if i reaches 20 then all the numbers divided equally into n
if(i === 20) {
// set value of divisible to true to cancel while loop
divisible = true;
}
}
}
// return the last value of n
return console.log("Answer: " +n);