Write a method called showTwos that shows the factors of 2 in a given integer. For example, consider the following calls:
showTwos(7);
showTwos(18);
showTwos(68);
showTwos(120);
These calls should produce the following output:
7 = 7
18 = 2 * 9
68 = 2 * 2 * 17
120 = 2 * 2 * 2 * 15
public class FactorsOf {
// this is a wrapper funtion to print one line only once
public void showTwos(int value) {
System.out.print(value + " = ");
showTwos1(value);
}
// actual recursive funtion
public void showTwos1(int value) {
if (value < 2) {
System.out.println(value);
return;
} else if (value % 2 == 1) {
System.out.println(value);
return;
} else if (value % 2 == 0 && value >= 2) {
System.out.print("2 * ");
showTwos1(value / 2);
}
}
public static void main(String[] args) {
// creating object and calling funtion
FactorsOf factors = new FactorsOf();
factors.showTwos(7);
factors.showTwos(18);
factors.showTwos(68);
factors.showTwos(120);
}
}
Output:
7 = 7
18 = 2 * 9
68 = 2 * 2 * 17
120 = 2 * 2 * 2 * 15