In: Computer Science
Must be in Java
Write a program called showTwos that shows the factors of 2 in a given positive integer (user input) in the range of [16,128]. For example, if user inputs 7, 18, 68, 120, the correctly working program should print the following:
7 = 7
18 = 2 * 9
68 = 2 * 2 * 17
120 = 2 * 2 * 2 * 15
For this we are firstly checking if the number is not in range of 16 to 128 ,then no two's multiples shown. If it is in range then we find how many 2's are there using % which gives remainder. So we check if number%2==0 means if it is fully divisible by 2 then increase count else stop the loop. We use this count to print multiples of 2
import java.util.Scanner;
public class showTwos {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
System.out.print("Enter positive integer between 16 to 128 ");
int number=scan.nextInt();
if((number<16)||(number>128)){
System.out.println(number+"="+number);
}
else {
int n = number;
int count = 0;
while (n > 0) {
if (n % 2 == 0) {
count++;
n = n / 2;
} else {
break;
}
}
String res = "2*";
for (int i = 1; i < count; i++) {
res = res + "2*";
}
System.out.println(number + "=" + res + n + " " + count);
}
}
}