Minimum Steps to One

后端 未结 4 1270
庸人自扰
庸人自扰 2021-01-01 23:12

Problem statement :

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 divis
4条回答
  •  猫巷女王i
    2021-01-02 00:01

    This works :)

    import java.util.Scanner;
    public class MinimumStepToOne {
    
     public static void main(String[] args){
        Scanner sscan = new Scanner(System.in);
        System.out.print("Give a no:" + " ");
    
        int n = sscan.nextInt();
        int count = 0;
        for(int i = 0; n > 1; i++){
    
            if(n%2 == 0){n /= 2; count++;}
            else if(n%3 == 0){ n /= 3; count++;}
            else { n -= 1; count++;}
    
        }
        System.out.println("your no is minimized to: " + n);
        System.out.println("The min no of steps: " + count);    
     }
    }
    

提交回复
热议问题