Find optimal weights which can be used to weigh all the weights in the range [ 1 , X ] | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findWeights ( int X ) { int sum = 0 ; int power = 0 ; while ( sum < X ) { sum = pow ( 3 , power + 1 ) - 1 ; sum /= 2 ; power ++ ; } int ans = 1 ; for ( int i = 1 ; i <= power ; i ++ ) { cout << ans << " ▁ " ; ans = ans * 3 ; } } int main ( ) { int X = 2 ; findWeights ( X ) ; return 0 ; }