Results 1 to 4 of 4

Thread: javascript code help.     submit to reddit submit to twitter

  1. #1
    New Merits
    Join Date
    Apr 2007
    Posts
    214
    BG Level
    4

    javascript code help.

    I have this assignment where I have to use javascript to list the prime numbers between 1-50. While I have the code to find and list these numbers, it lists them multiple times and I can't figure out why.
    anyways here is the code:
    =======================
    var x;
    x = 1;
    while(x<=50)
    {
    var isprime = true;

    for (i = 2; i <= x / 2; i++) {
    if ((x % i) == 0) {
    isprime = false;
    }
    if (isprime == true) {
    document.write(x + " is prime.<br/>");
    }
    }

    x=x+1
    }

    ==========================
    I am bad at formatting code so I apologize for any eye bleeding. Like I said, the code partially works, but for some reason it is listing the prime numbers multiple times. Any ideas? 4 hours before this is due.

  2. #2
    Ridill
    Join Date
    Feb 2006
    Posts
    11,977
    BG Level
    9

    Edit: nvm, I know what you're doing now. Move this code outside of the for loop:

    if (isprime == true) {
    document.write(x + " is prime.<br/>");
    }

    right before x=x+1

  3. #3
    New Merits
    Join Date
    Apr 2007
    Posts
    214
    BG Level
    4

    Awesome! Thanks

  4. #4
    Relic Horn
    Join Date
    Mar 2006
    Posts
    3,215
    BG Level
    7

    I think there's a [code] tag you can use to make it format properly, unless I'm thinking of the old forum setup.

Similar Threads

  1. Simple HTML Coding Help
    By Pirian in forum General Discussion
    Replies: 11
    Last Post: 2010-09-17, 18:28
  2. C++ easy code help
    By Skie in forum General Discussion
    Replies: 31
    Last Post: 2009-10-20, 05:10