Find optimal weights which can be used to weigh all the weights in the range [1, X]
Last Updated :
31 May, 2022
Given an integer X, the task is to find an optimal set of weights {w1, w2, w3, …, wn} such that we can weigh/determine all the weights from 1 to X using a two-sided weighing balance pan. Note that all the weights must be unique and n should be as minimum as possible.
Examples:
Input: X = 7
Output: 1 3 9
Weights |
Left Side |
Right Side |
1 |
1 |
1 |
2 |
2 + 1 |
3 |
3 |
3 |
3 |
4 |
4 |
1 + 3 |
5 |
5 + 1 + 3 |
9 |
6 |
6 + 3 |
9 |
7 |
7 + 3 |
1 + 9 |
Input: X = 20
Output: 1 3 9 27
Approach:
- One optimal approach is to use weights which are powers of 3 i.e. {1, 3, 9, 27, 81, 243, …}
- It can be proved through induction that using {1, 3, 9, 27, 81, …, pow(3, n)}, we can balance all the weights from 1 to (pow(3, n + 1) – 1) / 2.
- So, find the values of n such that all the values from 1 to X can be balanced and print the results.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
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;
}
|
Java
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);
}
}
|
Python3
def findWeights(X):
sum = 0
power = 0
while ( sum < X):
sum = pow ( 3 , power + 1 ) - 1
sum / / = 2
power + = 1
ans = 1
for i in range ( 1 , power + 1 ):
print (ans, end = " " )
ans = ans * 3
X = 2
findWeights(X)
|
C#
using System;
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++)
{
Console.Write(ans + " " );
ans = ans * 3;
}
}
static public void Main ()
{
int X = 2;
findWeights(X);
}
}
|
Javascript
<script>
function findWeights(X)
{
let sum = 0;
let power = 0;
let number = 3;
while (sum < X)
{
sum = number - 1;
sum = Math.floor(sum/2);
power++;
number *= 3;
}
let ans = 1;
for (let i = 1; i <= power; i++)
{
document.write(ans + " " );
ans = ans * 3;
}
}
let X = 2;
findWeights(X);
</script>
|
Time Complexity: O(logn)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...