Algorithm: Counterfeit Coin Problem (Divide and Conquer)

📢 This article was translated by gemini-3-flash-preview

Problem Description

You have $n$ coins. One of them is a counterfeit and is known to be lighter than the genuine coins. Using only a balance scale, find the counterfeit coin with the minimum number of comparisons.

Problem Analysis

Divide the $n$ coins into two equal parts:

  1. If $n$ is even, place the two halves ($1\cdots\frac{n}{2}$ and $\frac{n}{2}+1\cdots n$) on each side of the scale. The counterfeit coin is in the lighter half. Continue the search within that half using the same method.
  2. If $n$ is odd, place the two halves ($1\cdots\frac{n-1}{2}$ and $\frac{n+1}{2}+1\cdots n$) on each side of the scale. If one side is lighter, the counterfeit coin is in that part; continue the search there. If the two sides balance, then the middle coin (the $\frac{n+1}{2}$-th coin) is the counterfeit one.

C Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>

// coins: weight array; first, last: first and last indices of the array
int getCounterfeitCoin(int *coins, int first, int last);

int main(void){
    int coins[10] = {2,2,1,2,2,2,2,2,2,2};
    int tmp = getCounterfeitCoin(coins, 0, 9);
    printf("The %d-th coin is counterfeit\n", tmp + 1);
    return 0;
}

int getCounterfeitCoin(int *coins, int first, int last){
    int firstSum=0; int lastSum=0;
    int i;

    // Only two coins left
    if(first == last - 1){
        if(coins[first] < coins[last])
            return first;
        return last;
    }

    // Even number of coins
    if ((last-first+1)%2 == 0){
        for(i=first; i<first+(last-first)/2+1; i++){
            firstSum += coins[i];
        }
        for(i=first+(last-first)/2+1; i<last+1; i++){
            lastSum += coins[i];
        }

        if(firstSum < lastSum){
            return getCounterfeitCoin(coins, first, first+(last-first)/2);
        }else{
            return getCounterfeitCoin(coins, first+(last-first)/2+1, last);
        }
    }else{  // Odd number of coins
        for(i=first; i<first+(last-first)/2; i++){
            firstSum += coins[i];
        }
        for(i=first+(last-first)/2+1; i<last+1; i++){
            lastSum += coins[i];
        }

        if(firstSum < lastSum){
            return getCounterfeitCoin(coins, first, first+(last-first)/2-1);
        }else if(firstSum > lastSum){
            return getCounterfeitCoin(coins, first+(last-first)/2+1, last);
        }else{
            return first+(last-first)/2;
        }
    }
}