Write a static method named showTwos that shows the factors of 2 in a given inte
ID: 3724330 • Letter: W
Question
Write a static method named showTwos that shows the factors of 2 in a given integer. For example, the following calls produce the following output:
Call Output
showTwos(7); 7 = 7
showTwos(18); 18 = 2 * 9
showTwos(68); 68 = 2 * 2 * 17
showTwos(120); 120 = 2 * 2 * 2 * 15
The idea is to express the number as a product of factors of 2 and an odd number. The number 120, for example, has 3 factors of 2 multiplied by the odd number 15. For odd numbers (as in the first example of 7), there are no factors of 2, so you just show the number itself. Assume that your method is passed a number greater than 0.
Test your code with the following code file:
public class TestShowTwos {
public static void main(String[] args) {
showTwos(7); // 7 = 7
showTwos(18); // 18 = 2 * 9
showTwos(68); // 68 = 2 * 2 * 17
showTwos(120); // 120 = 2 * 2 * 2 * 15
}
}
Intro to java class help?
Explanation / Answer
TestShowTwos.java
public class TestShowTwos {
public static void main(String[] args) {
showTwos(7); // 7 = 7
showTwos(18); // 18 = 2 * 9
showTwos(68); // 68 = 2 * 2 * 17
showTwos(120); // 120 = 2 * 2 * 2 * 15
}
public static void showTwos(int n) {
while(n % 2 == 0) {
System.out.print("2 * ");
n = n / 2;
}
System.out.println(n);
}
}
Output:
7
2 * 9
2 * 2 * 17
2 * 2 * 2 * 15
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.