Min operations to reduce N to 1 by multiplying by A or dividing by B | Java program for the above approach ; Function to check if it is possible to convert a number N to 1 by a minimum use of the two operations ; For the Case b % a != 0 ; Check if n equal to 1 ; Check if n is not divisible by b ; Initialize a variable ' c ' ; Loop until n is divisible by b ; Count number of divisions ; Loop until n is divisible by c ; Count number of operations ; Check if n is reduced to 1 ; Count steps ; Return the total number of steps ; Driver Code ; Given n , a and b ; Function Call
import java . util . * ; class GFG { static int findIfPossible ( int n , int a , int b ) { if ( b % a != 0 ) { if ( n == 1 ) return 0 ; else if ( n % b != 0 ) return - 1 ; else return ( int ) n / b ; } int c = b / a ; int x = 0 , y = 0 ; while ( n % b == 0 ) { n = n / b ; x ++ ; } while ( n % c == 0 ) { n = n / c ; y ++ ; } if ( n == 1 ) { int total_steps = x + ( 2 * y ) ; return total_steps ; } else return - 1 ; } public static void main ( String s [ ] ) { int n = 48 ; int a = 3 , b = 12 ; System . out . println ( findIfPossible ( n , a , b ) ) ; } }