Problem:
Problem I: Memory Match

Memory match is a single-player game which employs a set of 2M cards. Each card is labeled with a
number between 1 and M on its face. For each number i (1 ≤ i ≤ M), there are exactly two cards which
have the number i. At the start of the game, all cards are shuffled and laid face down on a table. In each
turn you choose two cards and turn them face up. If two numbers on the cards are the same, they are
removed from the table. Otherwise, they are turned face down again (this is called a mismatch). When
you choose cards, you do not have to turn two cards simultaneously; you can choose the second card
after you see the number of the first card. The objective of the game is to remove all the cards with as
few mismatches as possible.

Royce A. Mitchell has extraordinary memory, so he can remember all the positions and the numbers of
the cards that he has already turned face up. Your task is to write a program that calculates the expected
number of mismatches, on average, when he plays the game optimally.

Input

The input consists of multiple datasets.

Each dataset consists of one even number N (2 ≤ N ≤ 1000) which denotes the number of cards in the
set.

The end of input is indicated by a line that contains a single zero. This is not part of the input and you
may not treat this line as a dataset.

Output

For each dataset, print the expected number of mismatches. Each output value may have an arbitrary
number of fractional digits, provided that the error is within 10-6.

Sample Input

2
4
6
8
10
52
0

Output for the Sample Input

0.0000000000
0.6666666667
1.3333333333
1.9238095238
2.5523809524
15.4435236099

Solution in C (judge verdict: Accepted)

/*
  AOJ 2139
  Title:Memory Mach
  @kankichi573
*/
#include <stdio.h>
#include <float.h>

double memo[501][1001];

double div_(int x,int y)
{
  return ((double)x)/((double)y);
}
double match_12(int n,int m) 
{
  return div_(n-2*m,(n-m)*(n-m-1));
}
double match_1st(int n,int m)
{
  return div_(m,n-m);
}
double match_2nd(int n,int m)
{
  return div_(n-2*m,n-m)*div_(m,n-m-1);
}
double nomatch(int n,int m)
{
  return div_((n-2*m)*(n-2*m-1)-(n-2*m),(n-m)*(n-m-1));
}


double kitaiti(	int n, // # of all cards
	        int m  // # of cards already opened
) 
{
  double ret;
  if(n==2 || n/2 <= m)
    return(0.0);

  if((ret=memo[n/2][m])!=0.0)
    return(ret);

  ret  = match_12(n,m)    * kitaiti(n-2,m);
  if(m>0)
    ret += match_1st(n,m) * kitaiti(n-2,m-1);
  if(m>0)
    ret += match_2nd(n,m) * (1.0+kitaiti(n-2,m));
  ret += nomatch(n,m)     * (1.0+kitaiti(n,m+2));
  memo[n/2][m]=ret;
  return(ret);
}

main()
{
  int n,i,j;
  while(scanf("%d",&n) && n)
    {
      for(i=0;i<500;i++)
	for(j=0;j<1000;j++)
	  memo[i][j]=0.0;

      printf("%2.7lf\n",kitaiti(n,0));
    }
  return(0);
}