简体   繁体   中英

javascript - Finding remainder of integer not working

I want to find (using JS) the greatest 3-digit number that

  • leaves a remainder of 1 when divided by 2
  • leaves a remainder of 2 when divided by 3
  • leaves a remainder of 3 when divided by 4
  • leaves a remainder of 4 when divided by 5
  • This is my code:

    var bool = false;
    for(var i = 999; bool == true; i = (i - 1)) {
       if(i % 2 == 1 && i % 3 == 2 && i % 4 == 3 && i % 5 == 4) {
          bool = true;
          alert(i);
       }
    }
    

    But it did not work (somehow there was no error messages, and the alert did not show up). So how can I find that 3-digit number? Thanks.

    The loop continuation condition for your loop is bool == true , which is false when the loop starts and so the loop will never execute. Use this instead:

    for(var i = 999; i > 0 && !bool; i = (i - 1)) {
    

    or this to strictly obey the "three-digit number" requirement:

    for(var i = 999; i >= 100 && !bool; i = (i - 1)) {
    

    I'd also suggest finding a better variable name than bool . found would be appropriate here.

    Your breaking condition is wrong here change it to:

    Here is Demo

    var bool = false;
    for(var i = 999; !bool; i--) {
    
       if(i % 2 == 1 && i % 3 == 2 && i % 4 == 3 && i % 5 == 4) {
          bool = true;
          alert(i);
       }
    }
    

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM