根据错排公式f[n]=(n-1)*(f[n-1]+f[n-2]) f[1]=0,f[2]=1
import java.io.BufferedInputStream;
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(new BufferedInputStream(System.in));
int nlen = 1001, i, n;
BigInteger[] num = new BigInteger[nlen];
num[1] = BigInteger.ZERO;
num[2] = BigInteger.ONE;
for (i = 3; i < nlen; i++) {
num[i] = num[i - 1].add(num[i - 2]).multiply(
BigInteger.valueOf(i - 1));
}
while (cin.hasNext()) {
n = cin.nextInt();
System.out.println(num[n]);
}
}
}
打表部分代码如下所示:
/*
* wrongsort.cpp
*
* Created on: 2011-10-10
* Author: bjfuwangzhu
*/
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
const int nmax = 1001;
string num[nmax];
int main() {
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif
int i, n;
num[1] = "0";
num[2] = "1";
num[3] = "2";
num[4] = "9";
num[5] = "44";
num[6] = "265";
num[7] = "1854";
num[8] = "14833";
num[9] = "133496";
num[10] = "1334961";
num[11] = "14684570";
num[12] = "176214841";
num[13] = "2290792932";
num[14] = "32071101049";
num[15] = "481066515734";
num[16] = "7697064251745";
num[17] = "130850092279664";
num[18] = "2355301661033953";
num[19] = "44750731559645106";
num[20] = "895014631192902121";
num[21] = "18795307255050944540";
num[22] = "413496759611120779881";
num[23] = "9510425471055777937262";
num[24] = "228250211305338670494289";
num[25] = "5706255282633466762357224";
num[26] = "148362637348470135821287825";
num[27] = "4005791208408693667174771274";
num[28] = "112162153835443422680893595673";
num[29] = "3252702461227859257745914274516";
num[30] = "97581073836835777732377428235481";
num[31] = "3025013288941909109703700275299910";
num[32] = "96800425246141091510518408809597121";
num[33] = "3194414033122656019847107490716704992";
num[34] = "108610077126170304674801654684367969729";
num[35] = "3801352699415960663618057913952878940514";
num[36] = "136848697178974583890250084902303641858505";
num[37] = "5063401795622059603939253141385234748764684";
num[38] = "192409268233638264949691619372638920453057993";
num[39] = "7503961461111892333037973155532917897669261726";
num[40] = "300158458444475693321518926221316715906770469041";
num[41] = "12306496796223503426182275975073985352177589230680";
num[42] = "516872865441387143899655590953107384791458747688561";
num[43] = "22225533213979647187685190410983617546032726150608122";
num[44] = "977923461415104476258148378083279172025439950626757369";
num[45] = "44006555763679701431616677013747562741144797778204081604";
num[46] = "2024301565129266265854367142632387886092660697797387753785";
num[47] = "95142173561075514495155255703722230646355052796477224427894";
num[48] = "4566824330931624695767452273778667071025042534230906772538913";
num[49] = "223774392215649610092605161415154686480227084177314431854406736";
-----------------------------
while (scanf("%d", &n) != EOF) {
cout << num[n] << endl;
}
return 0;
}