题解 | #Sum of Factorials#

Sum of Factorials

https://www.nowcoder.com/practice/42cb1c7f7344466b8cb1710cb12d06b1

思路

There's a fact that the sum of factorials from 1! to n! is strictly smaller than (n+1)!:


\sum_{i=1}^{n}{i!} = 1! + 2! + \dots + n! = n! (\frac{1!}{n!} + \frac{2!}{n!} + \dots + \frac{n!}{n!}) \leq n! n < (n+1)!

So when:


S = \sum_{i=1}^{t} x_i!, (x_i=x_j \Leftrightarrow i=j) \\
n! < S < (n+1)!

n! must be one of the x_i. Otherwise, S = \sum_{i=1}^{t}x_i \le \sum_{i=1}^{n-1}i! < n!, which is contradicts to n! < S.

And if S=n!, then \{x_i\} contains only \{n\}.

So we can design the algorithm as follow

实现

#include <iostream>
#include <array>

using namespace std;

int main()
{
    std::array<int, 11> F; // F[i] = i!
    F[0] = 1;
    for (int i = 1; i < 11; i++)
    {
        F[i] = (i) * F[i-1];
    }

    int n;
    while (cin >> n) {
        for (int i = 10; i >= 0; i--) {
            if (F[i] <= n) {
                n -= F[i];
            }
            if (n == 0) {
                break;
            }
        }
        if (n == 0) {
            cout << "YES" << endl;
        } else {
            cout << "NO" << endl;
        }
    }
}
全部评论

相关推荐

抱抱碍事梨a:三点建议,第一点是建议再做一个项目,把自我介绍部分顶了,第二点是中南大学加黑加粗,第三点是建议加v详细交流
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务