Skip to content

Instantly share code, notes, and snippets.

@EugenyB
Created March 3, 2016 20:17
Show Gist options
  • Save EugenyB/0cefbeed3eed686cf936 to your computer and use it in GitHub Desktop.
Save EugenyB/0cefbeed3eed686cf936 to your computer and use it in GitHub Desktop.
#include <iostream>
#define N 2000
void process(int n);
void set0(int k[N]);
void set1(int k[N]);
void copyarr(int from[N], int to[N]);
void mul(int arr[N], int k);
void add(int a[N], int b[N]);
void print(int a[N]);
using namespace std;
int main() {
int n;
while (true) {
cin >> n;
if (n == -1) break;
process(n);
}
return 0;
}
void process(int n) {
int f[N],fs[N],fprev[N],fsprev[N];
set0(f); set1(fs);
for (int i=2; i<=n; i++) {
copyarr(f,fprev);
copyarr(fs,fsprev);
copyarr(fsprev,f);
mul(f,i-1);
copyarr(fprev,fs);
add(fs,f);
}
print(f);
}
void print(int a[N]) {
int i=N-1;
while (a[i]==0 && i>=0) i--;
if (i==-1) cout << 0; else {
while (i>=0) {
cout << a[i--];
}
}
cout << endl;
}
void add(int a[N], int b[N]) {
int perenos = 0;
for(int i=0; i<N; i++) {
perenos += (a[i]+b[i]);
a[i] = perenos % 10;
perenos /= 10;
}
}
void mul(int arr[N], int k) {
int perenos = 0;
for (int i=0; i<N; i++) {
perenos = arr[i]*k+perenos;
arr[i] = perenos % 10;
perenos /= 10;
}
}
void copyarr(int from[N], int to[N]) {
for (int i=0; i<N; i++) {
to[i]=from[i];
}
}
void set1(int k[N]) {
set0(k);
k[0]=1;
}
void set0(int k[N]) {
for (int i=0; i<N; i++) k[i] = 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment