保存未知数量的整数,而不会花费太多时间/内存
Saving unknown amount of integers without taking too much time/memory
#include <iostream>
using namespace std;
unsigned long long divsum(unsigned long long x);
int main()
{
unsigned long long x;
cin >> x;
unsigned long long y[200000];
for (unsigned int i = 0; i < x; i++)
cin >> y[i];
for (unsigned int i = 0; i < x; i++){
cout << divsum(y[i]) << endl;
}
return 0;
}
unsigned long long divsum(unsigned long long x){
int sum = 0;
for(unsigned int i = 1; i <= x/2; i++){
if(x % i == 0)
sum += i;
}
return sum;
}
我正在做一个在线练习,它说第一行可能有 2000000 个案例,所以我做了一个数组,但是,当我提交解决方案时,它超过了时间......所以我想知道什么是替代和更快的方法来做到这一点?该程序现在运行良好,除了它超过了网站的时间限制。
您可以动态分配数组,因此在以下情况下它会更好地工作x < 200000
int main()
{
unsigned long long x;
cin >> x;
unsigned long long *y = new unsigned long long[x];
// you can check if new didn't throw an exception here
for (unsigned int i = 0; i < x; i++)
cin >> y[i];
for (unsigned int i = 0; i < x; i++){
cout << divsum(y[i]) << endl;
}
delete[] y;
return 0;
}
既然你知道数组的大小,请尝试vector
并reserve
。
int main()
{
unsigned long long x;
cin >> x;
unsigned long long var;
vector<unsigned long long> y;
y.reserve(x);
for (unsigned int i = 0; i < x; i++){
cin >> y[i];
}for (unsigned int i = 0; i < x; i++){
cout << divsum(var) << endl;
}
return 0;
}
并处理const &
const unsigned long long & divsum(const unsigned long long & x){
int sum = 0;
unsigned long long x2 = x/2
for(unsigned int i = 1; i <= x2; i++){
if(x % i == 0)
sum += i;
}
return sum;
}
我认为你的作业比你想象的要复杂。你的divsum(x( 函数应该返回 x 的所有除数的总和,对吧?在这种情况下,最好对 x 进行因式分解,并使用所有素数(带幂(计算此总和,其乘积等于 x。看看:
http://en.wikipedia.org/wiki/Divisor_function
有一些递归分解的方法 - 例如,如果您已经分解了所有数字直到 n 为止,您可以快速找到 (n + 1( 的因式分解。您还需要生成素数,前 2000000 个数字的 Erathosphene 筛子就可以了。
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 错误:字符数组的初始值设定项太多
- 对象实例化调用构造函数的次数太多
- Levenshtein 两个文件的距离花费了太多时间
- 我有三个 getline,但是一旦编译,输入就太多了
- 将使用太多的纹理插值器 - 带旋转的着色器
- C/C++:socket() 创建在循环中失败,打开的文件太多
- 在C++中使用线程查找友好号码比单个线程花费更多时间
- 使用Visual Studio在虚幻引擎中创建一个新的类c ++给了我太多的错误
- 读取串行命令花费太多时间
- 为什么 Boost unordered_map 在第一次插入时需要太多时间?
- BRK(0) 花费的时间是否太多?
- 打印所有可能有 4 个字母的单词的时间太多
- 列表上的气泡排序 - 在计算上花费太多时间
- GCC 构建时间不会从预编译标头中受益太多
- 保存未知数量的整数,而不会花费太多时间/内存
- 错误太多 (标准::时间<chrono>::时间点) (VS2015)
- 插入到unordered_map需要太多时间
- 在MFC/ c++中花费太多时间来构建
- OpenGL颜色缓冲每帧添加太多的帧时间