This page is still under construction.

Parts of this page are still being built. What you see may change.

Nim

Time limit1sMemory limit128 MB

Summary
Given a Nim position, count how many single-pile moves lead to a losing position (XOR of the remaining piles equals zero).
Level

Medium5 of 10

Topics
Game theory, Bit manipulation, Math
Solved
No attempts yet

Problem

Nim is a two-player game played with several piles of stones. The players alternate turns, and on a turn a player removes one or more stones from any single pile. Play ends when all the stones have been removed, and the last player to have moved wins. Given a position in Nim, determine how many winning moves there are in that position.

A position is called losing if the first player to move from it would lose under perfect play by both sides. A winning move is therefore a move that leaves the game in a losing position. A famous theorem classifies all losing positions. Suppose a Nim position has nn piles containing k1,k2,…,knk_1, k_2, \dots, k_n stones respectively; then there are k1+k2+⋯+knk_1 + k_2 + \dots + k_n possible moves. Write each kik_i in binary. Then the position is losing if and only if, among all the kik_i, there is an even number of 1's in every digit position — equivalently, the position is losing if and only if the XOR of the kik_i is 0.

Consider the position with three piles k1=7k_1 = 7, k2=11k_2 = 11, and k3=13k_3 = 13. In binary these values are:

  • 111
  • 1011
  • 1101

The rightmost digits contain an odd number of 1's, so this position is not losing. If k3k_3 were instead 12, every digit position would contain exactly two 1's and the position would become losing. Since a winning move is any move that leaves a losing position, removing one stone from the third pile is a winning move when k1=7k_1 = 7, k2=11k_2 = 11, and k3=13k_3 = 13. In fact there are exactly three winning moves from this position: remove one stone from any one of the three piles.

Input

The input contains several test cases. Each test case begins with a line giving the number of piles nn (1≤n≤10001 \le n \le 1000). The next line contains nn positive integers kik_i (1≤ki≤1,000,000,0001 \le k_i \le 1{,}000{,}000{,}000), the number of stones in each pile. The end of input is marked by a test case with n=0n = 0, which must not be processed.

Output

For each test case, output a single line containing the number of winning moves from the given Nim position.

Examples1

  1. Example 1

    Input
    3
    7 11 13
    2
    1000000000 1000000000
    0
    
    Expected output
    3
    0