On a positive integer, you can perform any one of the following 3 steps. 1.) Subtract 1 from it. ( n = n - 1 ) , 2.) If its divisible by 2, divide by 2. ( if n % 2 == 0 , then n = n / 2 ) , 3.) If its divisible by 3, divide by 3. ( if n % 3 == 0 , then n = n / 3 ). Now the question is, given a positive integer n, find the minimum number of steps that takes n to 1
Answers
Answered by
0
import java.util.Scanner;
public class MinStep{
public static void main( String args[] ){
Scanner sc= new Scanner(System.in);
int counter = 0;
System.out.println("Enter a positive integer:");
int num=sc.nextInt();
while(num!=1){
if( num % 3==0){
num/=3;
counter++;
}
else if(num % 2==0){
num/=2;
counter++;
}
else{
num = num - 1;
counter++;
}
}
System.out.println("The minimum number of steps it took= " + counter);
sc.close();
}
}
This is the program for your question in the java programming language.
Hope it helps.
Similar questions