Need Help with a Simple Javascript Problem Involving Even and Odd Checking



  • Hi Everyone,

    I was wondering if someone can help me with creating a Javascript function for the following problem :

    • There are x number of bananas
    • There are are 3 monkeys
    • If the number of bananas is EVEN then monkey one and two get ALL the bananas.
    • If the number of bananas is ODD, monkey three gets the extra banana.

    Thank you.



  • Hi there.

    When you think of checking for even or odd think the mod (%) operator.

    Here is one way to do it for all values greater than 0 :

    function bananas(x){
      let monkey_1 = 0;
      let monkey_2 = 0;
      let monkey_3 = 0;
      if(x == 1){
        monkey_3 = 1;
      }
      else if(x % 2 == 0){
        // x is EVEN
        monkey_1 = x / 2;
        monkey_2 = x / 2;
      } else {
        //X is ODD
        monkey_1 = (x-1) / 2;
        monkey_2 = (x-1) / 2;
        monkey_3 = 1;
      }
      console.log("For " + x + " Bananas");
      console.log("Monkey 1 gets: " + monkey_1 + " Bananas");
      console.log("Monkey 2 gets: " + monkey_2 + " Bananas");
      console.log("Monkey 3 gets: " + monkey_3 + " Bananas");
      console.log("-------------------------------");
    }
    

    Please let me know if this worked for you by selecting it as the correct answer. Thank you.



  • Hi there.

    When you think of checking for even or odd think the mod (%) operator.

    Here is one way to do it for all values greater than 0 :

    function bananas(x){
      let monkey_1 = 0;
      let monkey_2 = 0;
      let monkey_3 = 0;
      if(x == 1){
        monkey_3 = 1;
      }
      else if(x % 2 == 0){
        // x is EVEN
        monkey_1 = x / 2;
        monkey_2 = x / 2;
      } else {
        //X is ODD
        monkey_1 = (x-1) / 2;
        monkey_2 = (x-1) / 2;
        monkey_3 = 1;
      }
      console.log("For " + x + " Bananas");
      console.log("Monkey 1 gets: " + monkey_1 + " Bananas");
      console.log("Monkey 2 gets: " + monkey_2 + " Bananas");
      console.log("Monkey 3 gets: " + monkey_3 + " Bananas");
      console.log("-------------------------------");
    }
    

    Please let me know if this worked for you by selecting it as the correct answer. Thank you.



  • It is amazing that Avan finds the time to reply to guys like us! Kudos!


Log in to reply