Problem:
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.
Solution:
package com.basics;
import java.util.Scanner;
public class CountTheNumberOfDivisibles {
int number;
public static void main(String[] args) {
CountTheNumberOfDivisibles countTheNumberOfDivisibles = new CountTheNumberOfDivisibles();
countTheNumberOfDivisibles.getTheNumber();
System.out.println("the number of times one must repeatedly divide this number by 2 is: " + countTheNumberOfDivisibles.countTheNumberOfDivisibles());
}
public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number greater than 2");
number = scanner.nextInt();
if(number < 2){
number = 0;
System.out.println("the given number is less than 2. please give the number greater than 2");
}
scanner.close();
}
public int countTheNumberOfDivisibles(){
int count = 0;
while(true){
if(number < 2){
break;
}
else {
number = number - 2;
count++;
}
}
return count;
}
}
Output:
enter the number greater than 2
127
the number of times one must repeatedly divide this number by 2 is: 63
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.
Solution:
package com.basics;
import java.util.Scanner;
public class CountTheNumberOfDivisibles {
int number;
public static void main(String[] args) {
CountTheNumberOfDivisibles countTheNumberOfDivisibles = new CountTheNumberOfDivisibles();
countTheNumberOfDivisibles.getTheNumber();
System.out.println("the number of times one must repeatedly divide this number by 2 is: " + countTheNumberOfDivisibles.countTheNumberOfDivisibles());
}
public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number greater than 2");
number = scanner.nextInt();
if(number < 2){
number = 0;
System.out.println("the given number is less than 2. please give the number greater than 2");
}
scanner.close();
}
public int countTheNumberOfDivisibles(){
int count = 0;
while(true){
if(number < 2){
break;
}
else {
number = number - 2;
count++;
}
}
return count;
}
}
Output:
enter the number greater than 2
127
the number of times one must repeatedly divide this number by 2 is: 63
No comments:
Post a Comment