Find optimal weights which can be used to weigh all the weights in the range [ 1 , X ] | Java implementation of the approach ; Function to find the optimal weights ; Number of weights required ; Finding the value of required powers of 3 ; Optimal Weights are powers of 3 ; Driver code
import java . util . * ; public class GFG { static void findWeights ( int X ) { int sum = 0 ; int power = 0 ; int number = 3 ; while ( sum < X ) { sum = number - 1 ; sum /= 2 ; power ++ ; number *= 3 ; } int ans = 1 ; for ( int i = 1 ; i <= power ; i ++ ) { System . out . print ( ans + " ▁ " ) ; ans = ans * 3 ; } } public static void main ( String [ ] args ) { int X = 2 ; findWeights ( X ) ; } }