Write a method called showTwos that uses a while loop to sho

Write a method called showTwos that uses a while loop to show the factors of 2 in a given integer. For example the following calls should return the values shown showTwos(7) 7 = 7 showTwos(18) 18 = 2 * 9 showTwos(68) 68 = 2 * 2 * 17 showTwos(120) 120 = 2 * 2 * 2 * 15 showTwos(192) 192 = 2 * 2 * 2 * 2 * 2 * 2 * 3

Solution

/**
* @author
*
*/
public class ShowFactors {
   /**
   * @param args
   */
   public static void main(String[] args) {

       System.out.println(\"showTwos(7)\");
       showTwos(7);

       System.out.println(\"showTwos(18)\");
       showTwos(18);

       System.out.println(\"showTwos(68)\");
       showTwos(68);

       System.out.println(\"showTwos(120)\");
       showTwos(120);

       System.out.println(\"showTwos(192)\");
       showTwos(192);
   }

   /**
   * @param n
   */
   public static void showTwos(int n) {

       System.out.print(n + \" = \");
       int ip = n;
       while (n >= 0) {

           if (n % 2 == 1) {
               System.out.println(\" \" + n);
               break;
           } else {
               n = n / 2;
               System.out.print(\"2 * \");
           }
       }
   }
}

OUTPUT:

showTwos(7)
7 = 7
showTwos(18)
18 = 2 * 9
showTwos(68)
68 = 2 * 2 * 17
showTwos(120)
120 = 2 * 2 * 2 * 15
showTwos(192)
192 = 2 * 2 * 2 * 2 * 2 * 2 * 3

 Write a method called showTwos that uses a while loop to show the factors of 2 in a given integer. For example the following calls should return the values sho
 Write a method called showTwos that uses a while loop to show the factors of 2 in a given integer. For example the following calls should return the values sho

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site