Do pre-processing steps to remove the pairs of factor 2 and 5 (which combines together can generate a 0). Then do factorial calculation against preprocessed numbers, and only keep a single digit at each step. Why not just keep a single digit without pre-processing step? Because even if a digit is not zero, it could become zero after multiplying - so we need make sure kill those factors (2 and 5) first.
int N; intmain(){ ifstream fin("fact4.in"); ofstream fout("fact4.out"); fin >> N; vector<int> num(N, 0); for (int i = 0; i < N; ++i) { num[i] = i + 1; } int cnt = 0; for (auto &i : num) { while (i % 5 == 0) { i = i / 5; ++cnt; } } for (auto &i : num) { while (i % 2 == 0) { if (cnt == 0) break; i = i / 2; --cnt; } if (cnt == 0) break; } longlong r = 1; for (int i = 0; i < N; ++i) { r = (r * num[i]) % 10; } cout << r << endl; fout << r << endl; }