Trying to create a piece of code that return all numbers below 1000 that are multiples of three. This is the relevant piece of code.
<script>
var i = 1;
var mplesOf3 = [0];
var myNum = 0;
while (myNum < 1000){
(3 * i) = myNum;
mplesOf3.push(myNum);
i++;
};
alert(mplesOf3);
</script>
The code runs in a html page, hence the style tags and alert.
The code basically trying to do 3x1 then 3x2 then 3x3 so on and so forth until the result is over 1000. I came up with the concept days ago and I'm still not sure why its not running properly.
For the record I've seen other solutions to how to do this but because I'm learning and want to improve I want to know why this solution doesn't work.
Thank you in advance
Edit: I should have known the mistake would be something stupid. I wrote (3 x 1) = n on the pseudocode and just didn't spot the mistake because nothing seem wrong to me. Thank to all parties, will accept an answer when I can.
Your JavaScript engine should be telling you you have a syntax error (look in the web console if you're using a browser). You can't have an expression like (3 * i) on the left-hand side of an assignment. In JavaScript, the thing on the right of the = is evaluated, and assigned to the thing on the left.
Your algorithm would also result in 1002 being pushed, because you're not testing the result of setting myNum = 3 * i until after pushing.
Sticking with your original algorithm but fixing those two things:
var i = 1;
var mplesOf3 = [0];
var myNum;
while ((myNum = 3 * i) < 1000){
mplesOf3.push(myNum);
i++;
} // Note: No semicolon here, you don't put semicolons after blocks
// attached to control-flow statements
console.log(mplesOf3);
This bit:
while ((myNum = 3 * i) < 1000){
evaluates 3 * i, assigns the result to myNum, and then checks that that value is < 1000.
That said, it would probably be simpler (fewer variables, less multiplication) to use a for and myNum += 3 in the increment section:
var mplesOf3 = [0];
var myNum;
for (var myNum = 3; myNum < 1000; myNum += 3) {
mplesOf3.push(myNum);
}
console.log(mplesOf3);
There's also no particularly good reason to special-case the 0 like that, so I'd probably leave it out of the array initially and start counting from 0:
var mplesOf3 = [];
var myNum;
for (var myNum = 0; myNum < 1000; myNum += 3) {
mplesOf3.push(myNum);
}
console.log(mplesOf3);
This is invalid:
(3 * i) = myNum;
Instead, do this:
myNum = (3 * i);
I would do it this way, and this takes care that even the last one stays below 1000:
<script>
var i, mplesOf3;
mplesOf3 = [];
for (i=0; i<1000; i++){
if (i % 3 === 0){
mplesOf3.push(i);
}
}
alert(mplesOf3);
</script>
Update (see comments):
For better efficiency your code is better, and here is a complete fix that even takes care of the last value to be below 1000:
var i = 1;
var mplesOf3 = [0];
var myNum = 0;
while (myNum < 1000){
myNum = 3 * i;
myNum < 1000 && mplesOf3.push(myNum);
i++;
};
alert(mplesOf3);
Another improvement would be to avoid the comparison in each loop and always remove the last item from the final array:
var i = 1;
var mplesOf3 = [0];
var myNum = 0;
while (myNum < 1000){
myNum = 3 * i;
mplesOf3.push(myNum);
i++;
};
mplesOf3.pop();
alert(mplesOf3);
maybe your mistake is (3 * i) = myNum;
you just need to: myNum=(3 * i);
First name then assign a value;
Related
To do this you must multiply 6*5*4*3*2*1. To verify your loop is working correctly, the value you are looking for as a result is: 720
var dvDDG = document.querySelector("#ddg");
for(var i = 0; i < 7; i++) {
//remainder..
if( (i*7) == 720 ) {
dvDDG.innerHTML += i + "<br />";
}
}
I'm not entirely certain what you're trying to do with the code you have, it will simply check all numbers zero through six inclusive, and output the value which, when multiplied by seven, is equal to 720.
Since the highest value you'll get is 6 x 7 = 42 (nowhere near 720), you'll see nothing.
The pseudo-code for what you're after would be along the lines of:
fact = 1
for i = 2 to N inclusive:
fact = fact * i
print fact
Turning that into Javascript (or any procedural language for that matter) should be fairly simple, such as with:
function fact(n) {
res = 1
for (var i = 2; i <= n; i++) {
res = res * i;
}
return res
}
alert(fact(6))
It's fairly simple:
var factorial = 1;
var num = 6;
for (var i = 1; i <= num; i++){
factorial *= i;
}
There you go, your answer is the variable factorial. Just copy it into any output function you want. Be careful though, factorial can get pretty huge very fast. Try not to experiment on numbers that much larger that 6.
So I was thinking something like
number = 1;
maxnum = 32;
cat = true;
if (cat == true){
number + 1;
}
something along those lines, but I don't know how to implement that into making a constant changing line of number from 1 to 32; On the console.log.
maxnum = 32;
for(var i=0; i<maxnum; i++}{
console.log(i);
}
Use this:
var num = 1;
var maxnum = 32;
for(var i = num; i <= maxnum; i++){
console.log(i);
}
use the variable, i, in the for loop as a counter. Each round through the loop, 'i' will increment by one. CodeAcademy will give you some good practice and basic info on for loops. Eloquent Javascript is for more in depth study on the javascript language.
You can use a 'for' loop:
var maxnum = 32;
for (var i=1; i<maxnum; ++i) {
console.log(i);
}
You need to use a loop in your answer, either a for loop or a while loop.
If you change your if statement to a while loop, for example, and you can do this as follows.
number = 1;
maxnum = 32;
cat = true;
// Change "if" to "while" to make it a loop
while (cat == true){
// Add the following line to print:
console.log(number);
// Update the "cat" variable:
cat = (number < 32);
// Make sure this line uses assignment:
number += 1;
}
However, a for loop is a much cleaner solution. See the other answers posted here for examples of how to use a for loop.
var i = 1,
maxnum = 32;
while (i <= maxnum){
console.log(i++);
}
I'm doing the Euler project problem 2 in which the objective is to sum the even numbers of the fibonacci sequence that have a value of less than 4 million. I've searched a bit and I've seen several solutions using a while loop but nothing simple using a for loop. I'm curious why I'm returning zero with the following code:
var array = [];
array[0] = 0;
array[1] = 1;
var total = 0;
for(var i=2;total<=4000000;i++) {
array[i] = array[i-1] + array[i-2];};
for(var x=0;x<array.length;x++){
if(array[x]%2 === 0){
total += array[x]};};
alert(total);
I'm guessing the problem is in my for loop using the total variable. I couldn't get it to work using array[i]<=4000000 either and I'm really curious behind the why here. Anyone know why this is? What can I change in the for loop condition (second statement) to get a correct total here?
First of all there is an infinite loop at first for. Your condition must be array[i-1] < 4000000. After that your second for loop will find the correct result.
Also for the problem, you don't need to store all fibonacci numbers then find sum of even numbers.
You can calculate sum when calculating fibonacci.
var first = 0;
var second = 1;
var sum = 0;
for(var current=first+second; current < 4000000; current = first+second){
if(current%2 === 0){
sum+=current;
}
first = second;
second = current;
}
I fixed it for you.
var i, data = [ 0, 1 ], total = 0;
for (i = 2; i <= 4000000; i++)
{
data[i] = data[i - 1] + data[i - 2];
if (data[i] % 2 === 0)
{
total += data[i];
}
}
alert(total);
I'm not sure what you termination condition should be like, you say have a value of less than 4 million, but this is ambiguous. Maybe it should be total <= 4000000 or data[i] <= 4000000. Your phrasing is not precise enough.
Sorry but for me your code going in a dead loop. first "for" use total as check but it's never incremented. If you want This is a solution for fibonacci sequence based on dinamic programming with memoization tecnic.
var f1 = 1;
var f2 = 1;
for(var i = 2; i < 40000; i++){
console.info(i, f1, f2);
var temp = f1 + f2;
f1 = f2;
f2 = temp;
}
alert(f2);
This question could also be (depending on how you look at it) - How to use a for loop to do a basic math operation that adds up the sum of the multiples of 3
So I am doing Problem 1 of Project Euler.
I've (already) hit a steel-reinforced wall. I could use some help - with just a specific portion of the problem please (I am not looking for just an answer to the problem, but rather, an answer to my specific problem so I can carry on with trying to solve the remainder problem using any answer you guys provide me here)...
Anyways.
I (think I) created a for loop that will give me the multiples of 3. However, I'm trying to store the result of each iteration of the for-loop so that it adds up to the sum of those multiples i.e. I'm trying to store the result from each iteration of the loop - whether it be into an array or into a variable that takes the sum of the multiples - it doesn't matter to me - I wouldn't mind learning both methods.
I'm sure this sounds kind of confusing so let me paint my picture w/ an example...
I have a for-loop:
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i * 3);
WHAT DO I DO NEXT????
^ So I would think that this gives me x with a value of 3 upon the 1st iteration of the loop, x with a value of 9 on the 2nd loop, and x with a value of 18 on the final loop. That's correct, right? (if this were returning 18 I don't think I would need to store the values of each iteration into an array)
1st iteration:
i = 1; x = 0
Original equation...
(i * 3) + x
So...
(1 * 3) + (x = 0) = 3
So after completion of the 1st loop, x has a value of 3, right???
(Question: How would I store this value of x (which is 3) - how would I store it in an array while in this stage of the for loop?)
2nd iteration of loop:
i = 2; x = 3
(2 * 3) + (x = 3) = 9
(same question as before: how would I add this value to an array?)
3rd iteration:
i = 3; x = 9
(3 * 3) + (x = 9) = 18
Q: shouldn't this be the final value of x upon completion of the for loop??? For some reason, when I run the code, the final value of x is 9, and not 18
So, basically I am trying to add the sum of the 3 values...But what do I do next? I thought my for loop would add the result of the equation after each loop to x, but instead of ending up w/ 18 (the sum of 3 + 6 + 9), x's value was 9???
Should I use an array? If so, I'm thinking I could add the return value to an array, but I'm not sure how to add the result of each iteration of the loop to an array. Maybe the following?...
for (i = 1; i <= 3; i++) {
var array = [];
x = 0;
x += (i *3);
array.push(x);
};
^ I tried running that in jfiddle, but it would only add the last value of x (9) into the array... So how would I add the value of x to an array after each iteration of the for loop??? And I'm not seeing what's wrong with my for-loop to where it's returning a value of x as 9?
Also, I'm assuming the euler problems get significantly more difficult as we progress? If so, I've got a TON of work/practice to do....
THANKS IN ADVANCE...
Just create the array once, and push the result at each iteration to the array:
var array = [];
for (i = 1; i <= 3; i++) {
var x = 0;
x += (i *3);
array.push(x);
}
Or for that matter, just use this:
var array = [];
for (i = 1; i <= 3; i++) {
array.push(i *3);
}
Or to simply get the sum of the factors, use this:
var x = 0;
for (i = 1; i <= 3; i++) {
x += i *3;
}
You are declaring var x = 0 and var array = [] at every step of the loop, try something like:
var array = [], x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}
You can use like this:
and you have to define X out of the loop
var array = [],
x = 0;
for (i=1; i<4; i++){
x += (i*3);
array.push(x);
}
I want to push arrays containing random numbers (0 to 10) into a bigger array once the total of its contents is about to exceed 30. But the output is messed up.
var bigarray = new Array();
var smallarray = new Array();
var randNum = 0;
var total = 0;
for (var i = 0; i<10; i++){
randNum = (10*Math.random()).toFixed(0);
total = total + randNum;
if(total>30) {
bigarray.push(smallarray)
smallarray.length=0;
smallarray.push(randNum);
total = randNum;
} else {
smallarray.push(randNum);
}
}
alert(" BIG ARRAY IS "+bigarray);
two wrong things are visible on the first sight in the code
(1) instead of
randNum = (10*Math.random()).toFixed(0);
you probably want
randNum = Math.floor(11*Math.random());
Math.floor instead of toFixed() - see #kennebec comment
11 instead of 10 to return numbers 0 to 10, as 0 <= Math.random() < 1
(2) the following line pushes (many times) the reference to the same smallarray object.
bigarray.push(smallarray);
In the next step you clear the array with smallarray.length = 0. Because the array is not copied to the bigarray, but only referenced, the generated items are lost.
EDIT: I read your question wrong - the rest of the answer is fixed
You probably want to push the duplicate of the smallarray into bigarray, so replace the line above with the following:
bigarray.push(smallarray.slice(0));
You need another loop inside the main one to populate the smallarray, something like:
var bigarray = new Array();
for (var i = 0; i<10; i++){
// moving the variable declarations inside this loop means they are re-set for each small array
var smallarray = new Array();
// create the first entry for the small array
var randNum = Math.floor(11*Math.random());
var total = randNum;
// loop to populate the small array
while(total <= 30){
smallarray.push(randNum);
randNum = Math.floor(11*Math.random());
total += randNum;
}
bigarray.push(smallarray)
}
I made changes to you code and came up with this.
var bigarray = [];
var smallarray = [];
var randNum = 0;
var total = 0;
for (var i = 0; i < 10; i += 1) {
randNum = Math.floor(10 * Math.random()); // you will never have a value of 10?
total = total + randNum;
if (total > 30) {
bigarray.push(smallarray.slice())
smallarray.length = 0;
smallarray.push(randNum);
total = randNum;
} else {
smallarray.push(randNum);
}
}
alert(" BIG ARRAY IS " + bigarray);
On jsfiddle
Things I changed were:
Ran the code through a beautifier
Changed your use of new Array to []
{} and []
Use {} instead of new Object(). Use [] instead of new Array().
Because Object and Array can be overwritten by the user
Changed ++ to += 1
This pattern can be confusing.
Check out Code Conventions for the JavaScript Programming Language and jslint
Added array.slice when you push smallarray to bigarray, this makes a copy in this case. It is important to understand how javascript works, read Is JavaScript a pass-by-reference or pass-by-value language? Without using slice, which makes a copy as the array only contains primitives, when you set the length of the array to 0, then the data was lost.
Changed your use of number.toFixed to Math.floor so that randNum remains a number
Note: Math.random returns a floating-point, pseudo-random number in the range [0, 1] that is, from 0 (inclusive) up to but not including 1 (exclusive)
Whether your code now produces your expected out, I can not be sure from your description but this should be a good starting point.
var bigarray = new Array();
var smallarray = new Array();
var randNum = 0;
var total = 0;
for (var i = 0; i < 10; i++) {
for (var j = 0; j < smallarray.length; j++) {
total = total + smallarray[j];
}
if (total <= 30)
{
randNum = Math.floor((Math.random() * 10) + 1);
smallarray.push(randNum);
}
else {
bigarray.push(smallarray.slice(0));
smallarray.length = 0;
}
total = 0;
}
alert(" BIG ARRAY IS " + bigarray);