题解 | #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;
        }
    }
}
全部评论

相关推荐

白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
白火同学:只是实习的话,你这份简历应该也差不多了。真要优化的话,因为面实习的话,没有开发经验,面试更重视技术栈水平。 1、重视JavaSE的基础吧,集合、泛型算是比较基础的基础,多线程、反射、JVM内存模型才是基础; 2、技术栈写到具体的点,比如Elasticsearch的使用写到某个点,限制面试官自由发挥,防止问了相关问题最后又答不上,如果真没把握建议不写,降低面试官的心理预期; 3、技术栈不要重复,比如技术栈第二条和第八条可以合并改为“熟悉Redis中间件,包括基本数据结构、缓存策略、持久化机制,了解缓存三剑客及其解决方案,并有相关项目经验。”; 4、项目指标量化,比如“达到xx秒的响应速度”(不过这个就有点偏校招社招的要求了,实习简历不写也无伤大雅)。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务