Write a Java program that can take a positive integer greater than 2 as input and write out the number of times onemust repeatedly divide this number by 2 before getting a value less than 2.
package java_problems_datastructures;
import java.util.Scanner;
public class DivideByTwo {
// this counter tracks the number of times we have divided by 2
static int count = 1;
// we will use recursion to find the value
static int divideByTwo(int enteredValue) {
// calling the method in a loop till we met the desired condition
if (enteredValue / 2 >= 2) {
divideByTwo(enteredValue / 2);
count++;
}
return count;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value ");
int value = input.nextInt();
while (value <= 2) {
System.out.println("please enter value greater than 2 ");
value = input.nextInt();
}
System.out.println("number of times divide before getting less than two is : " + divideByTwo(value));
input.close();
}
}
Output:
Please enter a value
1
please enter value greater than 2
8
number of times divide before getting less than two is : 3