【问题标题】:why the execution of the follwing function gives Runtime Errors: Abort signal from abort(3) (SIGABRT)?为什么执行以下函数会出现运行时错误:来自 abort(3) (SIGABRT) 的中止信号?
【发布时间】:2020-04-10 19:44:17
【问题描述】:
   **There is a structure in my program**

    #include<bits/stdc++.h> 
    using namespace std;
    #define N 1000005 
    #define MAX 1e18 
    // Vector to store powers greater than 3 
    vector<long long int> powers; 

    // vector to store perfect squares 
    vector<long long int> squares; 


    void computation()
    { 
     unordered_map<long long int,long long int> mp;
     unordered_map<long long int,long long int> ms;
    squares.push_back(1); 
    ms[1]=1;
    for (long long int i = 2; i <N; i++)  
    { 
        // pushing squares

        squares.push_back(i * i); 
        ms[i*i]=1;
             if (ms[i]==1) 
                continue; 

        long long int temp = i; 

        // run loop until some 
        // power of current number 
        // doesn't exceed MAX 
        while (i * i <= MAX / temp)  
        { 
            temp *= (i * i); 
             if(mp[temp]==0){
            powers.push_back(temp);
            mp[temp]=1;
             }

        } 
    } 
    sort(powers.begin(),powers.end());
    sort(squares.begin(),squares.end());
    } 


在计算函数调用后的主函数中,任何操作都会产生 sig 错误

  int main(){

  computation();

  return 0;

  }

如何使用 map 正确重写? 对不起,如果这个问题已经被问过了,我在看的时候无法理解。

【问题讨论】:

  • 即使我使用 unsigned long long int 错误仍然存​​在

标签: algorithm dictionary runtime-error c++14 sigabrt


【解决方案1】:

更正了该行中缺少的括号:

while(i * i <= (MAX / temp)){

不过,对于 N 的取值范围为 10^5,它的幂超出了 10^10 和 10^20s 的范围,这就是为什么它在编译器的容差限制后被中止的原因。目前,在 C++ 中没有可以处理这么多值的数据类型。查看执行时间和输出。尝试优化您的代码或为您的问题找到另一种算法。对于N=10005这样小的N值,程序执行成功。

TIO 编译器:Try it online!

Ideone:Demo - Ideone online compiler

您可以尝试的另一种解决方案是以字符串格式存储整数,对于较大的字符串大小,这将花费大量计算时间,但可以根据加法和小乘法轻松优化乘法。

【讨论】:

  • 如果我使用这个算法呢??
  • 在上面的链接中......我在 o(10^9) 中只找到了直到 10^18 的正方形,但仍然给出了 segabrt
  • 请告诉我应该如何有效地存储高达 10^18 的正方形
  • @rocking 你的链接ide.geeksforgeeks.org/jvCHaChm8p有编译器错误。
  • @rocking 上面的程序(写在答案中),实际上运行效率很高,只是编译器无法打印如此大量的巨大值,仅此而已。为了验证,它可以打印奇数位置的值。
猜你喜欢
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多