www.webdeveloper.com
Results 1 to 3 of 3

Thread: Javascript novice problem

Hybrid View

  1. #1
    Join Date
    Jun 2011
    Posts
    5

    Javascript novice problem

    I wrote this code which should add all the numbers that are dividable by 3 or 5 below 1000, however I can't get to print the answer on the screen.

    Code:
    <html>
    <head>
    	<title>Problem 1 project euler</title>
    </head>
    <body>
    	<script>
    	var x = 0
    	var _tel = 0
    	while (_tel <= 1000)
    	{
    		if (((_tel/3)) = ((math.round((_tel/3))))
    			{
    			var x = x + _tel;
    			}
    		else if (((_tel/5)) = ((math.round((_tel/5))))
    			{
    			var x = x + _tel;
    			}
    		else
    			{
    			}
    		var _tel = _tel + 1
    	}
    	document.write (x)
    	</script>
    </body>
    </html>
    I hope anyone can tell me why it doesnt work.

    Appel

  2. #2
    Join Date
    Aug 2007
    Posts
    3,767
    Because of the extra vars. Only use var when declaring the variable. And because == tests equality, = is an assignment. And it's Math.round! Also, I had to remove some of those extra parentheses because I couldn't could easily if you had the correct number.
    Code:
    if (_tel/3 == Math.round(_tel/3))
    {
    	var x = x + _tel;
    }
    else if (_tel/5 == Math.round(_tel/5))
    {
    	var x = x + _tel;
    }
    else
    {
    }
    var _tel = _tel + 1;
    I also suggest that you always use a ; to finish a statement.

    A more efficient, easier to read version would be this.
    Code:
    var x = 0;
    for (var _tel = 0; _tel<1000; _tel++) {
        if (_tel%5 == 0 || _tel%3 == 0) {
            x+=_tel;
        }
    }
    document.write(x);
    Where % returns the remainder of _tel divided by 5 and 3 respectively.
    Last edited by Declan1991; 06-19-2011 at 07:40 PM.

  3. #3
    Join Date
    Jun 2011
    Posts
    5
    thanks man! that worked =)

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles