Weighing#1993

Weighing (Editorial)

Divide all the balls into three groups that are as equal in size as possible. If the number is not divisible by , the sizes of the groups will differ by at most one ball. Two groups of equal size are placed on the pans of the balance. As a result of one weighing, we determine in which of the three groups the heavy ball is located.

Thus, after one weighing, the problem with balls is reduced in the worst case to a problem with balls. Therefore, ⌈log_3n⌉ weighings are sufficient to guarantee the detection of the heavy ball.

Second solution. Let be the largest exponent for which the inequality 3^p < n holds. Then the minimum number of weighings required to guarantee the detection of the heavy ball is p + 1.

Example

For balls, a single weighing is sufficient. If the pans of the balance are in equilibrium, then the heavier ball was not placed on the balance.

In the case of balls, we divide them into groups of balls each. By placing one group on each pan of the balance, a single weighing allows us to determine which group contains the heavy ball.

If there are balls, divide them into three groups as follows: , and balls. In this case, the two groups of balls are placed on the pans of the balance.

Algorithm implementation

Read the number of balls .

scanf("%d",&n);

Compute and print the answer.

res = ceil(log(n) / log(3));
printf("%.0lf\n",res);  

Algorithm implementation – loop

Read the number of balls .

scanf("%d",&n); 

Compute and print the answer.

res = 0; p = 1;
while (p < n)
{
  p = p * 3;
  res++;
}

printf("%d\n",res);  

Java implementation

import java.util.*;

public class Main
{
  public static void main(String []args)
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();   
    double res = Math.ceil(Math.log(n) / Math.log(3));
    System.out.printf("%.0f\n",res);
    con.close();
  }
}    

Python implementation

Read the number of balls .

n = int(input())

Compute and print the answer.

print(int(math.ceil(math.log(n) / math.log(3))))